Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rust peekable double reference

Why does a peekable iterator return a double reference in an Option?

struct Foo {}
let mut foovec = vec![];
foovec.push(Foo {});
let mut iter = foovec.iter().peekable();
let next = iter.peek();

next is an Option<&&Foo>, not an Option<&Foo>.

How do I get it to be the latter?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I do not want to use .into_iter() because I do not want to consume the vec. I just want a borrowed reference to the Foo struct wrapped in an Option.

>Solution :

peek yields references to whatever you’re iterating over. If that’s also references, it’ll yield double references. You can use the copied Option adapter to remove that level of indirection:

struct Foo {}
let mut foovec = vec![];
foovec.push(Foo {});
let mut iter = foovec.iter().peekable();
// use `copied` here to go from Option<&&_> to Option<&_>
let next = iter.peek().copied();

Alternatively, you can just call next after you checked that you want the peeked value:

struct Foo {}
let mut foovec = vec![];
foovec.push(Foo {});
let mut iter = foovec.iter().peekable();
if is_okay(iter.peek()) {
    let next = iter.next(); // `next` has type `&Foo`
}

You could even use pattern matching to remove one level of indirection:

if let Some(&next) = iter.peek() {
    // `next` has type `&Foo` in this block
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading