【问题标题】:How to convert a string to an int?如何将字符串转换为int?
【发布时间】:2019-10-25 17:39:10
【问题描述】:

根据type conversion 示例,使用int.convert() 进行字符串到int 的转换。但是在 Ballerina 1.0.0 中不起作用:

$ ballerina version
Ballerina 1.0.0
Language specification 2019R3
$ cat test.bal 
public function main() {
    string x = "42";
    int|error y = int.convert(x);
}
$ ballerina build test.bal 
Compiling source
        test.bal
error: .::test.bal:3:19: undefined function 'convert'
$

还有<int> 提到的elsewhere 在SO 中也不起作用:

$ ballerina version
Ballerina 1.0.0
Language specification 2019R3
$ cat test.bal 
public function main() {
    string x = "42";
    int|error y = <int>x;
}
$ ballerina build test.bal 
Compiling source
        test.bal
error: .::test.bal:3:19: incompatible types: 'string' cannot be cast to 'int'
$

【问题讨论】:

  • 你能试试这样的吗:int val = check &lt;int&gt;strVal;我不是芭蕾舞专家,但我在网上找到了一些东西。尝试在演员表之前使用check。

标签: ballerina


【解决方案1】:

Ballerina v1.0 及更高版本,您可以将string 转换为int,如下所示:

import ballerina/lang.'int as langint;

public function main() {
    string x = "42";
    int|error y = langint:fromString(x);
}

【讨论】:

  • 完美运行。 fromString 中提供的文档不知何故我在第一次阅读时错过了...
  • 也可以像这样导入内置的int包。 import ballerina/lang.'int; 并将函数称为 int | error y = 'int:fromString(x);。以' 开头的标识符称为分隔标识符。一种用例是处理关键字冲突。
【解决方案2】:

从 Ballerina swan lake 版本开始,您可以简单地进行类型转换 (see examples)。不需要额外的导入。

public function main() {
    string x = "42";
    int|error y = int:fromString(x);
}

【讨论】:

    猜你喜欢
    • 2015-11-12
    • 2018-05-08
    • 1970-01-01
    • 2022-06-27
    • 2013-04-24
    • 2021-08-01
    • 1970-01-01
    • 2011-10-02
    相关资源
    最近更新 更多