Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through a RefCell wrapped Vec with Rust

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.

like image 650
Noi Sek Avatar asked Feb 25 '26 21:02

Noi Sek


1 Answers

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.

like image 134
Noi Sek Avatar answered Feb 28 '26 11:02

Noi Sek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!