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];
&x.iter()
}
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.
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.
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.