The use statement brings items from external modules or the standard library into your current scope, allowing you to reference them without their full path. It is essential for reducing verbosity and organizing code, supporting both direct imports and wildcard imports for entire modules.
You typically place use statements at the top of your file or inside a specific scope. For example, to import a specific function from the standard library, you write:
use std::thread;
use std::time::Duration;
fn main() {
// No need to write std::thread or std::time::Duration here
thread::sleep(Duration::from_secs(2));
}
If you need to import multiple items from the same parent module, you can group them to keep the code clean:
use std::collections::{HashMap, HashSet};
fn main() {
let map = HashMap::new();
let set = HashSet::new();
}
For complex module structures, you can use the as keyword to rename an imported item, which is helpful when dealing with naming conflicts or when you want a shorter alias:
use std::collections::HashMap as Map;
fn main() {
let my_map: Map<String, i32> = Map::new();
}
Be cautious with wildcard imports (use module::*), as they can pollute your namespace and make it unclear where an item originates. While convenient for quick scripts, they are generally discouraged in production code:
// Avoid this in large projects
use std::io::*;
fn main() {
// Is `read` from io::Read or a local function?
// read(&mut buffer);
}
Finally, remember that use only affects the current scope. If you need to re-export an item to make it available to other modules, you must use the pub use syntax:
// In lib.rs or a module file
pub use crate::internal::helper_function;
// Now other modules can use `crate::helper_function`
This approach keeps your public API clean while hiding internal implementation details.