❮ STDIN
❯
- std::io
- String
- stdin
- read_line
- expect
Rust - read input from STDIN
- Module std::io
- String::new() - Creates a new mutable empty string
- &mut name passes a reference of the variable to the function as mutable variable. & indicates it is a reference.
- read_line reads a line from the command line
examples/stdin/hello-name/src/main.rs
use std::io; fn main() { let mut name = String::new(); println!("Please type in your name:"); io::stdin() .read_line(&mut name) .expect("Failed to get input"); println!("Hello {}, how are you?", name); }
Please type in your name: Foo Bar Hello Foo Bar , how are you?
Two problems:
- The response looks broken. It has a newline after the name.
- After the prompt the program waits on a new line.