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

前端 未结 3 673
星月不相逢
星月不相逢 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:37

    Using the non-lexical lifetimes feature (only in nightly) and a fixed-length slice pattern you can move out of an array:

    #![feature(nll)]
    
    #[derive(Debug)]
    struct Foo;
    
    fn bar(foo: Foo) {
        println!("{:?}", foo);
    }
    
    fn main() {
        let v: [Foo; 3] = [Foo, Foo, Foo];
        let [a, b, c] = v;
    
        bar(a);
        bar(b);
        bar(c);
    }
    

    However, this solution does not scale well if the array is big.

    An alternative, if you don't mind the extra allocation, is to box the array and convert it into a Vec:

    fn main() {
        let v: [Foo; 3] = [Foo, Foo, Foo];
        let v = Vec::from(Box::new(v) as Box<[_]>);
    
        for a in v {
            bar(a);
        }
    }
    

    If the array is very big, that may be an issue. But then, if the array is very big, you should not be creating it in the stack in the first place!

提交回复
热议问题