Sub topic 2
Fixing Unresolved Names and Imports
Assume basic Rust syntax, Cargo commands, and an introduction to ownership and references. Rust diagnostics usually identify the failing code precisely. Read the error code, message, highlighted span, and suggested help text before changing code.
Fixing unresolved names and imports
An unresolved-name error means Rust cannot find a variable, function, type, or module in the current scope. Check spelling first. Then check whether the item is declared before use or imported from another module.
fn main() {
let count = 3;
println!("{cnt}"); // error[E0425]: cannot find value `cnt`
}The compiler may suggest count. For an item in another module, import it explicitly:
use std::collections::HashMap;
fn main() {
let mut scores = HashMap::new();
scores.insert("Ada", 10);
println!("{scores:?}");
}Fixing immutable assignment errors
Bindings are immutable by default. Add mut when the binding itself must change.
fn main() {
let total = 0;
total += 1; // error[E0384]
}The fix is:
fn main() {
let mut total = 0;
total += 1;
println!("{total}");
}A mutable binding does not make all data reachable through it mutable. The type and ownership rules still apply.
Fixing use of moved values
A move transfers ownership. After moving a String, the original binding cannot be used.
fn main() {
let name = String::from("Ferris");
let greeting = name;
println!("{name} {greeting}"); // error[E0382]
}Choose the smallest appropriate fix:
- Borrow with
&namewhen the second operation only reads. - Clone with
name.clone()when both bindings must own separate data. - Restructure the code so only one owner remains.
Understanding borrow checker conflicts
Rust permits many shared borrows or one mutable borrow, but not both at the same time. The borrow must also remain valid for every use.
fn main() {
let mut values = vec![1, 2, 3];
let first = &values[0];
values.push(4); // error[E0502]
println!("{first}");
}Copy the integer before mutating the vector. The copy ends the borrow.
fn main() {
let mut values = vec![1, 2, 3];
let first = values[0];
values.push(4);
println!("{first}");
}Exercise
When should you clone a moved String instead of borrowing it?
Show answer
Clone it when both parts of the program must own independent String values. Borrow it when the second use only needs temporary read access.