如何在 Ballerina 中从命令行读取 int?

Sam*_*isa 6 ballerina

any choice = io:readln("Enter choice 1 - 5: ");
Run Code Online (Sandbox Code Playgroud)

我似乎无法将输入转换为 int。

检查和匹配都会给出相同的错误

var intChoice = <int>choice;
match intChoice {
    int value => c = value;
    error err => io:println("error: " + err.message);
}
Run Code Online (Sandbox Code Playgroud)

c = check <int>choice;
Run Code Online (Sandbox Code Playgroud)

给出

error: 'string' cannot be cast to 'int'
Run Code Online (Sandbox Code Playgroud)

我查看了https://ballerina.io/learn/by-example/type-conversion.html并研究了https://ballerina.io/learn/api-docs/ballerina/io.html#readln但没有运气。

我究竟做错了什么?

sha*_*024 5

看起来这是any -> int转换中的一个错误。

如果使用 更改选择变量类型string或将变量定义语句更改为赋值语句var,则两种方法都有效。请参考下面的例子。

import ballerina/io;

function main(string... args) {
    // Change the any to string or var here.
    string choice = io:readln("Enter choice 1 - 5: ");
    int c = check <int>choice;
    io:println(c);

    var intChoice = <int>choice;
    match intChoice {
        int value => io:println(value);
        error err => io:println("error: " + err.message);
    }
}
Run Code Online (Sandbox Code Playgroud)

更新- 正如@supun 在下面提到的,这不是any->int转换中的错误,而是我不知道的实现细节。

  • 这个答案不正确。正如 /sf/users/474751931/ 所解释的,`io:readln()` 函数返回一个 `string`,因此您必须首先将字符串转换为 int。 (2认同)