I want to learn Rust and am making a small program to deal with sound ques. I have a function with this signature:
fn edit_show(mut show: &mut Vec<Que>) {
show.sort_by(|a, b| que_ordering(&a.id, &b.id));
loop {
println!("Current ques");
for l in show {
println!("{}", que_to_line(&l));
}
}
}
I get an error:
use of moved value: 'show'
I cannot find anything on how to fix this. This seems like an odd error for sort since (I assume) if I was to do this in the main function where I pass in the value which seems quite useless.
Solution
Your problem is in this line:
for l in show {
...
}
This consumes the vector show
. If you want to just borrow it's elements, you should write:
for l in &show {
...
}
If you want to borrow them mutably, write for l in &mut show
.
Explanation
The Rust for loop expects a type that implements IntoIterator
. First thing to note: IntoIterator
is implemented for every Iterator
. See:
impl<I> IntoIterator for I where I: Iterator
Now lets search for the Vec
impls:
impl<T> IntoIterator for Vec<T> {
type Item = T
...
}
impl<'a, T> IntoIterator for &'a Vec<T> {
type Item = &'a T
...
}
impl<'a, T> IntoIterator for &'a mut Vec<T> {
type Item = &'a mut T
...
}
Here you can see that it's implemented for the Vec
directly, but also for references to it. I hope these three impl blocks speak for themselves.