Looping through a RefCell wrapped Vec with Rust

2019-07-30 12:34发布

问题:

I have a struct that contains a RefCell for storing mutable values within a vector, and I'd like to loop over its values.

Adding an element causes no problems, but when attempting to convert the borrowed vector into an iterator it throws:

error: cannot move out of borrowed content [E0507]

Why does the borrow even matter, if it's immutable? I don't understand why the compiler would mark this as a potential issue when the content of the variable doesn't even change.

I can get around the ownership issue by cloning it, but why do I need to do that in the first place? Cloning the structure I'm trying to loop over is probably going to have a high CPU cost and I'd prefer not to have to do it if possible.

Example of what I'm trying to achieve:

fn main() {
    use std::cell::RefCell;
    let c = RefCell::new(vec![1, 2, 3]);

    let arr = c.borrow();

    for i in arr.into_iter() {
        println!("{}", i);
    }
}

Is there something I'm missing here or is Rust being overly cautious about this?

Would appreciate it if someone could fill any gaps in my understanding of how this works.

回答1:

It appears the issue was in there being a difference between Vec.into_iter and Vec.iter. To solve, change:

for i in arr.into_iter() {
    println!("{}", i);
}

to:

for i in arr.iter() {
    println!("{}", i);
}

As described in Effectively Using Iterators In Rust.