2.10 The use Keyword: Bringing Paths into Scope
The use keyword shortens the paths needed to refer to items (functions, types, modules) defined elsewhere, making code less verbose.
2.10.1 Importing Items
Instead of writing the full path repeatedly, use brings the item into the current scope.
// Bring the `io` module from the standard library (`std`) into scope
use std::io;
// Bring a specific type `HashMap` into scope
use std::collections::HashMap;
fn main() {
// Now we can use `io` directly instead of `std::io`
let mut input = String::new(); // String::new() is an associated function
println!("Enter your name:");
// stdin(), read_line(), and expect() are methods
io::stdin().read_line(&mut input).expect("Failed to read line");
// Use HashMap directly
let mut scores = HashMap::new(); // HashMap::new() is an associated function
scores.insert(String::from("Alice"), 10); // insert() is a method
// trim() is a method
println!("Hello, {}", input.trim());
// get() is a method, {:?} is debug formatting
println!("Alice's score: {:?}", scores.get("Alice"));
}
String::new()andHashMap::new()are associated functions acting like constructors.io::stdin()gets a handle to standard input.read_line(),expect(),insert(),trim(), andget()are methods called on instances or intermediate results.read_line(&mut input)reads a line into the mutable stringinput. The&mutindicates a mutable borrow, allowingread_lineto modifyinputwithout taking ownership (more on borrowing later)..expect(...)handles potential errors, crashing the program if the preceding operation (likeread_lineor potentiallyget) returns an error orNone.ResultandOption(covered next) offer more robust error handling.
Note: Running this code in environments like the Rust Playground or mdbook might not capture interactive input correctly.
2.10.2 Comparison with C
C’s #include directive performs textual inclusion of header files before compilation. Rust’s use statement operates at a semantic level, importing specific namespaced items without code duplication, leading to faster compilation and clearer dependency tracking.