2.9 use
Statements and Namespacing
The use
statement brings items from a module path into the current scope, avoiding repeated fully qualified paths.
2.9.1 Bringing Names into Scope
use std::io; fn main() { let mut input = String::new(); println!("Type something:"); io::stdin().read_line(&mut input) .expect("Failed to read line"); println!("You typed: {}", input); }
String::new()
creates a new, empty string (with a heap-allocated buffer) that can be modified.io::stdin().read_line(&mut input)
reads a full line of input from standard input and appends it toinput
. The&mut input
argument allows the function to modify the string..expect("Failed to read line")
handles possible errors by terminating the program with an error message if reading fails.- For readability,
.expect
is on a new line afterread_line()
. Method calls can be chained with.
, clarifying multi-line expressions.
Note: When you run this code directly in mdbook or the Rust playground, user input is not captured, so the string remains empty.
2.9.2 Comparison with C
C uses #include
to copy the contents of header files. Rust’s approach is more precise, bringing only specified names into scope instead of duplicating entire file contents.