I'm trying to make the following code work:
struct IntHolder {
ints: Vec<i32>,
}
impl IntHolder {
fn special_int(&self) -> Option<i32> {
return None;
}
fn all_ints(&self) -> impl Iterator<Item=&i32> {
return self.special_int().iter().chain(self.ints.iter());
}
}
fn main() {
let tst = IntHolder{ints: vec![0, 1, 2]};
for o in tst.all_ints() {
println!("{}", o)
}
}
But I get this error:
|
10 | return self.special_int().iter().chain(self.ints.iter());
| ------------------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| |
| returns a value referencing data owned by the current function
| temporary value created here
Oddly enough, if I change the function call to just inline None
instead of calling the function that returns an option, it works:
struct IntHolder {
ints: Vec<i32>,
}
impl IntHolder {
fn special_int(&self) -> Option<i32> {
return None;
}
fn all_ints(&self) -> impl Iterator<Item=&i32> {
return None.iter().chain(self.ints.iter());
}
}
fn main() {
let tst = IntHolder{ints: vec![0, 1, 2]};
for o in tst.all_ints() {
println!("{}", o)
}
}
Does anyone know how to make this work, or why it only seems to break when I call a function to generate the option?
(This is toy code to illustrate the problem I'm having. In my actual code, I have a struct which holds a vector of objects, and also sometimes has a special object that can be computed from the other fields. I want to return an iterator that iterates over the special object if it can be computed, and then iterates over all the objects in the vector. I'd also like to avoid having to do heap allocations if I can.)
question from:
https://stackoverflow.com/questions/65853143/trouble-chaining-option-and-struct-field-using-iterator-interface 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…