rust - 有没有办法检查用户是否使用 text_io 的 read!() 宏输入了一个整数?

标签 rust

我想检查用户是否输入了整数。如果他们没有,我想将他们重定向回输入问题:

println!("Place Your Chip");
let mut y_col: usize;

loop {
    y_col = read!();
    // Check if user entered in a integer or not
    if y_col < 1 || y_col > 6 {
        println!("Column space is 1 to 6");
        continue;
    } else {
        y_col -= 1;
    }
    if game.check_column(y_col) {
        println!("\t\t\t\t\t\t\t\tThe column you choose is full");
        continue;
    }
    break;
}

最佳答案

read!是通过杀死线程来处理错误,这样调用者就不需要担心它们了。这就是为什么 try_read!存在:

#[macro_use]
extern crate text_io; // 0.1.7

fn main() {
    let mut y_col: Result<usize, _>;

    y_col = try_read!();
    match y_col {
        Ok(v) => println!("Got a number: {}", v),
        Err(e) => eprintln!("Was not a number ({})", e),
    }
}
$ cargo run
123
Got a number: 123

$ cargo run
moo
Was not a number (could not parse moo as target type of __try_read_var__)

关于rust - 有没有办法检查用户是否使用 text_io 的 read!() 宏输入了一个整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57501789/

相关文章:

enums - 如何告诉编译器我返回的枚举的变体总是没有生命周期?

data-structures - 为什么 VecDeque 比 Vec 慢?

types - 无法正确获取 Rust 类型

rust - 分配给解除引用的 self -怎么办?

rust - 如何将格式良好的表格打印到控制台?

rust - Rust:如何将可变变量传递给函数

rust - dead_code 和未使用的 lint 有什么区别?

rust - 如何实现 `From<some trait' s 关联类型>?`

rust - 是否可以使用宏生成结构?

python - 从 Python 调用 Rust 时出错