How to iterate over Rc<Vec<String>>?

The following function doesn't seem to work

fn useRcOnSomething(rc : Rc<Vec<String>>) {
    println!("{:?}", rc);
    for i in rc {
        println!("{}", i);
    }
}

I thought Rc enables us to borrow immutable references to the contained value, however I am unable to iterate over the contained Vec<String> in the code above. How do I proceed?


Solution 1:

Rc cannot be iterated directly because it does not implement IntoIterator. You can call iter to deference it to get the owned string vector and spawn an immutable iterator over it.

fn useRcOnSomething(rc : Rc<Vec<String>>) {
    println!("{:?}", rc);
    for i in rc.iter() {
        println!("{}", i);
    }
}

Solution 2:

I thought Rc enables us to borrow immutable references to the contained value, however I am unable to iterate over the contained Vec<String> in the code above. How do I proceed?

The for loop goes through the IntoIterator trait. Because IntoIterator works on self, that's basically where the buck stops, and since Rc does not implement IntoIterator, it stops at failure. That is what the error message tells you (kinda, it also tells you that rc could be an Iterator but that's even less likely):

  = help: the trait `Iterator` is not implemented for `Rc<Vec<String>>`
  = note: required because of the requirements on the impl of `IntoIterator` for `Rc<Vec<String>>`

So the way to iterate is is to get at something which is iterable from the Rc, you can do that by either invoking the relevant method from slice as Joe_Jingyu suggests, or by actually getting a slice from the Rc:

    for i in &*rc {
        println!("{}", i);
    }

which amounts to the same (impl IntoIterator for &[T] simply calls iter).