Using “moved” values in a function

2019-09-03 20:33发布

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.

标签: sorting rust
1条回答
Anthone
2楼-- · 2019-09-03 21:10

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.

查看更多
登录 后发表回答