The name is not visible where you use it. For a variable, check the spelling and that it is declared in the same or an outer block. For a type or function from the standard library or a crate, add a use line, and for a crate also add it to Cargo.toml. The compiler usually prints the exact use line to add.
Checked with rustc 1.93.0, Windows 11
Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.
Rust only sees names that are declared in the current block or an enclosing one, that are brought in with use, or that are in the prelude (Vec, String, Option, Result, and a few more). Everything else, including HashMap, must be imported. The two error codes differ only in the kind of name:
E0425: a value (variable, function, constant) was not found.
E0433: the first part of a path (a type or module) was not found.
fn main() {
let total = 3 + 4;
println!("{}", totl);
}
text
error[E0425]: cannot find value `totl` in this scope
--> src/main.rs:3:20
|
3 | println!("{}", totl);
| ^^^^ help: a local variable with a similar name exists: `total`
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0425`.
Fix the spelling (total). If the spelling is right, the variable was declared in an inner block, a different function, or after the point where it is used; move the declaration outward or pass the value in as a parameter.
error[E0433]: failed to resolve: use of undeclared type `HashMap`
--> src/main.rs:2:20
|
2 | let mut ages = HashMap::new();
| ^^^^^^^ use of undeclared type `HashMap`
|
help: consider importing this struct
|
1 + use std::collections::HashMap;
|
error: aborting due to 1 previous error
For more information about this error, try `rustc --explain E0433`.
Add the use line the compiler shows:
src/main.rsrust
use std::collections::HashMap;
fn main() {
let mut ages = HashMap::new();
ages.insert("ada", 36);
println!("{:?}", ages.get("ada"));
}
text
Some(36)
For a type from an external crate, such as serde_json::Value, the crate must also be in [dependencies] in Cargo.toml (cargo add serde_json), otherwise the message is "use of unresolved module or unlinked crate".
Adding use lines by guesswork. Use the path the compiler prints; the same name often exists in several modules (std::fmt::Result and std::io::Result, for example).
Expecting a .rs file to be found without mod name; in its parent. See the thread on modules.