How to read user input in Rust?

前端 未结 10 1899
情歌与酒
情歌与酒 2021-01-31 07:50

Editor\'s note: This question refers to parts of Rust that predate Rust 1.0, but the general concept is still valid in Rust 1.0.

I intend to

10条回答
  •  你的背包
    2021-01-31 08:06

    from https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html#processing-a-guess

    use std::io;
    
    fn main() {
        println!("Guess the number!");
    
        println!("Please input your guess.");
    
        let mut guess = String::new();
    
        io::stdin().read_line(&mut guess).expect("Failed to read line");
    
        println!("You guessed: {}", guess);
    }
    

    While there are many different ways of doing this in rust I think this is the simplest to implement.

    use std::io;
    // ...
        let mut input = String::new();
        io::stdin().read_line(&mut input).expect("Failed to read line");
    
        println!("Your input was `{}`", input);
    // ...
    

提交回复
热议问题