What is the difference between (&vector).into_iter() and &vector.into_iter()?

type Data = (u8, u8);

fn main() {
    let v = vec![(5, 4), (5, 3)];

    // new vector which has pairs which add to 9
    // let f: Vec<&Data> = &v
    let f: Vec<&Data> = (&v)
        .into_iter()
        .filter(|d| {
            d.0 + d.1 == 9
        })
        .collect();
    println!("v {:?}", v);
    println!("f {:?}", f);
}

(&v).into_iter(): Iterator returns items of &Data, Does what I want. Took me a while to figure out I need to add to add the brackets. The question is what does &v mean and how does it compare? Thanks.

The difference is operator precedence -- &v.into_iter() means &(v.into_iter()).

But you can also use v.iter() to get the borrowed iterator.

4 Likes

Thanks. What I really wanted to do was put the vector through different filters and what I was doing was adding another level of indirection to the data. I had another go and finally got it to work without going Vec<&data>, `Vec<&&Data>'

// #[derive(Debug)]
// struct Data(u8, u8);
type Data = (u8, u8);

fn main() {
    let v = vec![(5, 4), (5, 3)];
    // let v = vec![Data(5, 4), Data(5, 3)];

    let v: Vec<Data> = v
        .into_iter()
        .filter(|d| {
           println!("d {:?}", d);
            d.0 + d.1 == 9
        })
        .collect();
    println!("v {:?}", v);
    let v: Vec<Data> = v
        .into_iter()
        .filter(|d| {
           println!("d {:?}", d);
            d.0 + d.1 != 9
        })
        .collect();
    println!("v {:?}", v);
}