use and paths
A path names an item in the module tree, such as crate::config::Settings. A use declaration brings a path into scope under a short name so you can stop writing the long version.
Detailed Explanation
Every item in Rust has one canonical path. std::collections::HashMap is the full name of that type, in the same way that a file has a full directory path. You can always write the long path at the point of use. use exists only so that you do not have to.
That leads to the single most useful thing to understand here: use changes what you type, never what compiles. It does not copy code, does not include a file, and does not make a private item accessible. If use fixes a name-resolution error, the item was already reachable. If the item is private, use fails with the same privacy error you would get from writing the path out in full. Bringing a module into your crate is the job of mod; bringing a package into your crate is the job of Cargo.toml.
Paths come in two flavours. An absolute path starts from a crate root: crate:: for your own crate, or the package name for a dependency, as in serde_json::Value. A relative path starts from the current module and may be prefixed with self:: (this module) or super:: (the parent module). Use absolute paths when the item lives far away, and super:: when a child module reaches back to a sibling, since that survives the parent being renamed.
The forms of use you will meet:
use std::collections::HashMap;— bring in one item.use std::io::Write as IoWrite;— rename, which resolves clashes between two traits or types with the same final segment.use std::collections::{HashMap, HashSet};— nested list.use std::io::{self, Read};— brings in bothioandio::Read.use std::collections::*;— a glob. Avoid it outside tests and preludes, because it makes the origin of a name invisible to a reader and exposes you to new names appearing when you upgrade a dependency.pub use crate::client::Client;— a re-export. The name becomes part of your public API, which is how crates present a flat, curated surface over a deep private module tree.
Style conventions in the community are worth following. Bring functions' parent modules into scope rather than the functions themselves, so a call site reads fs::read_to_string(...) and tells the reader where the function came from. Bring types, traits, and enums in directly, so you write HashMap rather than collections::HashMap. Traits must be in scope for their methods to be callable, which is why you sometimes use a trait and never name it again.
The standard prelude explains why your first program compiles without any imports at all. A small set of items — Option, Result, String, Vec, Box, Clone, Iterator, and a few dozen others — is injected into every module automatically. That is why Some(3) and String::from("hi") work with no use line. Anything outside the prelude, including HashMap, must be imported or written in full.
The cost of use is close to zero at runtime and at compile time. The real cost is readability: an unfamiliar short name with no clue to its origin slows a reader down, and glob imports multiply that problem.
Code Examples
use std::collections::HashMap; // a type: import it directly
use std::fmt::Write as FmtWrite; // renamed, so it does not clash with std::io::Write
use std::fs; // a module: call functions as fs::read_to_string(..)
fn main() -> Result<(), Box<dyn std::error::Error>> {
// `Result`, `Box`, `String` and `Vec` come from the prelude: no import needed.
let text = fs::read_to_string("hosts.txt")?;
let mut counts: HashMap<&str, usize> = HashMap::new();
for line in text.lines() {
*counts.entry(line.trim()).or_insert(0) += 1;
}
let mut report = String::new();
// `write!` needs the `FmtWrite` trait in scope, even though we never name it.
write!(report, "{} distinct hosts", counts.len())?;
println!("{report}");
Ok(())
}mod config {
pub struct Settings {
pub port: u16,
}
}
mod server {
// `super::` reaches back to the parent module, then down into a sibling.
use super::config::Settings;
pub fn start(settings: &Settings) {
println!("port {}", settings.port);
}
mod internals {
pub fn helper() {
// `self::` is the current module; `crate::` is the crate root.
self::deeper();
crate::server::start(&crate::config::Settings { port: 1 });
}
fn deeper() {}
}
}
// A re-export: callers of this crate write `Settings`, not `config::Settings`.
pub use config::Settings;Common Gotchas
`use` does not import a file
writing `use crate::parser::parse;` for a `src/parser.rs` that no module declared gives `error[E0432]: unresolved import`. The missing piece is `mod parser;` in the parent, not another `use`.
Trait methods need the trait in scope
calling `reader.read_to_string(&mut s)` without `use std::io::Read;` produces `error[E0599]: no method named 'read_to_string' found`. The method exists; the name is not visible. This is the most common confusing import error in Rust.
`pub use` is part of your public API
re-exporting a type from a dependency means a major version bump in that dependency becomes a breaking change for your users. Re-export deliberately, not by habit.
Glob imports lose to explicit ones
if a glob brings in a name that also exists locally or in an explicit `use`, the explicit name wins rather than causing an ambiguity error. Convenient, but it means a glob can quietly do nothing.