如何将字符串转换为整数?

How to convert a string to an int?

根据 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> 中提到的 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'
$

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

import ballerina/lang.'int as langint;

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

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

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