The answers above, as @freinn correctly points out, are now out of date. As of Rust 1.0, read_line()
requires the caller to pass in a buffer, rather than the function creating & returning one. The following code requires Rust 1.26+ (further simplifying error handling).
Note the response is trimmed using trim_end()
. This ensures the newline entered by the user will not be part of the response, which would split the greeting across two lines.
Note also the example below is robust in the case the user does not provide a response:
use std::io::stdin;
type Result<T, E = Box<dyn std::error::Error>> = std::result::Result<T, E>;
fn main() -> Result<()> {
println!("Hello, there! What is your name?");
let mut buffer = String::new();
// `read_line` returns `Result` of bytes read
stdin().read_line(&mut buffer)?;
let res = match buffer.trim_end() {
"" => "Ah, well I can respect your wish to remain anonymous.".into(),
name => format!("Hello, {name}. Nice to meet you!"),
};
println!("{res}");
Ok(())
}