The Rust Programming Language
The Rust Programming Language

The Rust Programming Language — References and Borrows — Understanding Values by Reference and Borrows

The pain of use after move errors finally ends!

Ankit Tanna
3 min readOct 22, 2023

--

In one of our previous examples we say an instance where use after move error was observed. Please have a look at the snippet which causes that error:

fn print_years(years: Vec<i32>) {
for year in years.iter() {
println!("{}", year);
}
}

fn main() {
let years = vec![2001, 2002, 2003, 2004]; // alloc()

print_years(years); // transfer the ownership of years to print_years()
print_years(years);
}

You must be aware that the variable years deallocation responsibility is with print_years(). So when the first time the method print_years() is called, years memory is marked as available. So when the method print_years() runs the second time, we get the use after move error.

We understood that this can be solved by making the print_years() return years and we create a new copy of the variable years2 as shown below:

fn print_years(years: Vec<i32>) {
for year in years.iter() {
println!("{}", year);
}
return years;
}

fn main() {
let years = vec![2001, 2002, 2003, 2004]; // alloc()

let years2 = print_years(years); // transfer the ownership of years…

--

--