我要检查用户是否输入了整数。如果他们没有,我想把他们引向输入问题:

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!的目的是通过终止线程来处理错误,以便调用方不必担心它们。这就是为什么存在:

#[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/

10-14 10:34