Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
318 views
in Technique[技术] by (71.8m points)

rust - Trouble chaining option and struct field using iterator interface

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The problem is that iter takes a reference to the value rather than consuming it, returning an iterator that references a value that belongs to the function.

Try using into_iter() instead:

return self.special_int().into_iter().chain(self.ints.iter());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...