Sub topic 5
Fixing unresolved names and imports
This chapter assumes you can read the parts of a rustc diagnostic (code, message, span, help). It also assumes you know basic let bindings, functions, and mod declarations, and that you can run cargo check. The goal is to turn "cannot find ..." and "unresolved import ..." errors into a short list of causes you can check in order.
What "unresolved" means
Before type checking or borrow checking, the compiler runs name resolution. It matches every identifier in your code (a variable, function, type, module, or trait) to a declaration visible at that point. If no declaration matches, compilation stops with an error that says it cannot find the name.
Unresolved-name errors are usually cheap to fix. The compiler often has a good guess and prints it in a help: line. Still, the same message can come from several different causes, so you need to know which one you have.
| Code | Typical message | Usual cause |
|---|---|---|
| E0425 | cannot find value, function, or variable `x` in this scope | Typo, wrong scope, or missing definition |
| E0412 | cannot find type `T` in this scope | Missing `use` or a misspelled type |
| E0433 | failed to resolve: use of undeclared type or module `X` | Missing `use` for the first segment of a path |
| E0432 | unresolved import `a::b` | The path in a `use` line does not exist |
| E0599 | no method named `m` found | The trait that provides the method is not in scope, or the method does not exist |
| E0603 | `item` is private | The item exists but is not `pub` |
| E0583 | file not found for module `m` | `mod m;` has no matching file |
Typos and the wrong scope
The simplest case is a misspelled variable.
fn main() {
let count = 3;
println!("{}", cnt);
}
// Fix: use the name that is actually defined.
// println!("{}", count);rustc reports error[E0425]: cannot find value 'cnt' in this scope. When a similarly named binding exists, it adds help: a local variable with a similar name exists: 'count'. Rust names are case-sensitive, so Count and count are different names.
If you see no similar-name hint, the name may exist but be out of scope. A let binding lives only in the block where it is declared.
fn main() {
{
let message = "hello";
}
println!("{message}");
}
// Fix: declare the binding in the outer block.
// let message = "hello";
// println!("{message}");The inner block ends before the println!, so message no longer exists. The same applies to variables declared inside if, match arms, loops, and closures. When the value must outlive the block, declare it outside and assign inside.
Missing `use` declarations
Most standard library types are not in the prelude, which is the small set of names Rust imports automatically. Vec, String, Option, and Result are in it. HashMap is not.
fn main() {
let mut scores = HashMap::new();
scores.insert("Ana", 10);
println!("{:?}", scores);
}
// Fix: import the type.
// use std::collections::HashMap;Here rustc reports E0433: failed to resolve: use of undeclared type 'HashMap'. The help text reads consider importing this struct: use std::collections::HashMap;. If you use HashMap as a type annotation, as in let m: HashMap<String, i32>, the code is E0412 instead. The cause and fix are the same.
Copy the suggested use line to the top of the file. When the help lists several candidates, check that you pick the right one. For example, Result could be std::fmt::Result, std::io::Result, or the prelude one, and they are not interchangeable.
Methods that need a trait in scope
A trait's methods are callable only when the trait itself is in scope. This produces a confusing error, because the type clearly has the method.
use std::fs::File;
fn main() {
let mut file = File::open("notes.txt").unwrap();
let mut text = String::new();
file.read_to_string(&mut text).unwrap();
println!("{text}");
}
// Fix: bring the trait into scope.
// use std::io::Read;The error is E0599: no method named 'read_to_string' found for struct 'File' in the current scope. A note says items from traits can only be used if the trait is in scope, and the help names std::io::Read. Read the note before assuming you misspelled the method. If the help does not mention a trait, the method may truly not exist for that type, and you should check the documentation.
Unresolved imports and module paths
E0432 means the use line itself is wrong. rustc points at the first segment of the path that it cannot find. Three causes account for most cases.
- A misspelled segment. For example,
use std::collection::HashMap;instead ofcollections. - A module that was never declared. In Rust, creating a file does not add it to the crate. You must declare it with
mod. - A crate that is not a dependency.
use rand::Rng;fails untilrandis listed inCargo.toml.
The module case catches many learners. Suppose src/utils.rs exists and main.rs contains the code below.
// src/main.rs
mod utils;
use utils::double;
fn main() {
println!("{}", double(21));
}// src/utils.rs
pub fn double(x: i32) -> i32 {
x * 2
}Without the mod utils; line in main.rs, the use line fails with E0432: unresolved import 'utils'. With mod utils; but no file at src/utils.rs or src/utils/mod.rs, you get E0583: file not found for module 'utils'. Both fail at the same line of intent, but the fixes differ.
For a missing crate, add it with Cargo rather than editing by hand.
cargo add rand
cargo checkRust 2018 and later resolve the first segment of a path as a local item, a crate in Cargo.toml, or std. A crate you have not added is therefore reported as unresolved even if it is installed elsewhere on your machine.
Privacy errors look like missing names
An item that exists but is private is reported as a privacy error, E0603. It is easy to confuse with an unresolved name.
mod shapes {
fn area(width: u32, height: u32) -> u32 {
width * height
}
}
fn main() {
println!("{}", shapes::area(2, 3));
}
// Fix: make the function public.
// pub fn area(width: u32, height: u32) -> u32 {rustc says error[E0603]: function 'area' is private and adds a note pointing to the definition. Items in a module are private to that module and its children by default. Make the item pub only if it is meant to be part of the module's interface. The same rule applies to struct fields, where you get E0616 when you read a private field from outside.
A checklist for any "cannot find" error
The diagram shows the order in which to check causes. It goes from the cheapest check to the most structural.
In practice, run cargo check after each change. Fixing one missing import often removes several errors at once, because later errors that used the same name were just consequences of the first one.
Edge cases worth knowing
- Glob imports hide the source.
use std::collections::*;brings in many names but makes later errors harder to trace. Prefer explicit imports so that a missing name points to one clear line. - Name clashes are a different error. Importing two items with the same name gives
E0252, not an unresolved error. Rename one withuse std::fmt::Result as FmtResult;. - Macros resolve separately. A missing macro reports
cannot find macro 'name' in this scope. For your own macros,#[macro_use]or ausepath may be required, and order in the file can matter formacro_rules!. - Enum variants need a path. Writing
Redinstead ofLight::RedgivesE0425. Either use the full path or adduse Light::*;(oruse Light::Red;). self,super, andcrate. In a nested module,use crate::utils::double;starts at the crate root.use super::double;starts at the parent module. Starting from the wrong root is a frequent cause ofE0432.
Exercises
Exercise
This program fails with E0599 on the write_all call. The type has the method, so why does the error appear, and what one line fixes it?
use std::fs::File;
fn main() {
let mut file = File::create("out.txt").unwrap();
file.write_all(b"hello").unwrap();
}
Show answer
write_all is provided by the std::io::Write trait, and trait methods can be called only when the trait is in scope. Add use std::io::Write; at the top of the file. The note "items from traits can only be used if the trait is in scope" in the diagnostic points to this cause.
Exercise
You create src/config.rs containing pub fn load() {} and write use config::load; in main.rs. rustc reports E0432. What is missing, and which different error would you get if you added mod config; but then deleted the file?
Show answer
main.rs needs the declaration mod config;, because creating a file does not add it to the crate. If mod config; is present but neither src/config.rs nor src/config/mod.rs exists, rustc reports E0583, file not found for module config.