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 to input. The &mut input argument allows the function to modify the string.
  • .expect("Failed to read line") handles potential errors by terminating the program with an error message if reading fails.
  • expect is placed on a new line after read_line() for readability; method calls can be chained with . in Rust, improving clarity in multi-line expressions.

Note: When you run this code directly in mdbook or in the 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 the specified names into scope instead of duplicating entire file contents.