read user input in rust

To read user input in Rust, you need to use the stdin module from the io module. First, you'll need to import the io module:

main.rs
use std::io;
13 chars
2 lines

Then, you can read user input using the stdin function on the io module:

main.rs
let mut input = String::new();
io::stdin().read_line(&mut input).expect("Failed to read line");
96 chars
3 lines

This code reads a line of user input from the console and stores it in a mutable String variable called input.

Finally, you can print the user's input using println!:

main.rs
println!("You entered: {}", input);
36 chars
2 lines

Here's the full example:

main.rs
use std::io;

fn main() {
    println!("Please enter some input:");

    let mut input = String::new();
    io::stdin().read_line(&mut input).expect("Failed to read line");

    println!("You entered: {}", input);
}
216 chars
11 lines

related categories

gistlibby LogSnag