Extend lifetime of variable

后端 未结 1 1795
伪装坚强ぢ
伪装坚强ぢ 2020-12-03 22:38

I\'m trying to return a slice from a vector which is built inside my function. Obviously this doesn\'t work because v\'s lifetime expires too soon. I\'m wonderi

相关标签:
1条回答
  • 2020-12-03 23:37

    You can't forcibly extend a value's lifetime; you just have to return the full Vec. If I may ask, why do you want to return the slice itself? It is almost always unnecessary, since a Vec can be cheaply (both in the sense of easy syntax and low-overhead at runtime) coerced to a slice.

    Alternatively, you could return the iterator:

    use std::iter;
    
    pub fn find<'a>(&'a self, name: &str) -> Box<Iterator<Item = &'a Element> + 'a> {
        Box::new(self.iter_elements()
           .filter(move |&elem| elem.name.borrow().local_name == name))
    }
    

    For now, you will have to use an iterator trait object, since closure have types that are unnameable.

    NB. I had to change the filter closure to capture-by-move (the move keyword) to ensure that it can be returned, or else the name variable would just passed into the closure pointer into find's stack frame, and hence would be restricted from leaving find.

    0 讨论(0)
提交回复
热议问题