How do I move values out of an array one at a time?

前端 未结 3 688
星月不相逢
星月不相逢 2020-12-06 10:02

I have ownership of an array of size 3 and I would like to iterate on it, moving the elements out as I go. Basically, I would like to have IntoIterator implemen

3条回答
  •  渐次进展
    2020-12-06 10:45

    You may use array of Option instead array of Foo. It has some memory penalty of course. Function take() replaces value in array with None.

    #[derive(Debug)]
    struct Foo;
    
    // A method that needs an owned Foo
    fn bar(foo: Foo) { println!("{:?}", foo); }
    
    fn main() {
        let mut v  = [Some(Foo),Some(Foo),Some(Foo)];
    
        for a in &mut v {
            a.take().map(|x| bar(x));
        }
    }
    

提交回复
热议问题