How to generate Iterator while keep the data source inside function


What I trying to do is write a function that returns an iterator. However I want to keep the actual data closured, and the caller do not want to deal with the actual data. Pretty much like the following code(except it won’t work)

fn get_iterator<'a>() -> &'a Iterator<Item=&'a u64> {
    let x = vec![1,2,3,4,5];

The above code will give error error: borrowed value does not live long enough. I understand that it is caused that iter() will use references to vector x and x will be destructed once the function return.

So is it possible to achieve the goal? Thanks!


Not in that way, no. You have to keep the data around for the entire time it’s used. One option would be to find or make an iterator that takes the source data by value, and returns references, but I suspect that restructuring the code may be a better option.

You can’t, by the way, return &'a Iterator<Item=&'a u64> since the iterator is also destroyed.


Is there any built in support for this? or do I have to implement all that manually?


Not that I can think of. I haven’t yet looked through the itertools crate, though. There’s usually some very nifty tools there, so I wouldn’t be surprised if someone made something like that.


Sometimes you can move the container into an iterator, like vec![1,2,3,4,5].into_iter(). With this you’d be returning std::vec::IntoIter, and all the values are owned.


Great! It’s actually so handy.

Originally I was trying to return a cycled iterator of a certain vector. And it seems that I cannot not do this:

    let x = vec![1,2,3,4,5];

Because Clone is not implemented for std::vec::IntoIter.

Anyway, thank you very much!