首页 > 解决方案 > 错误说值在循环迭代中移动到先前的位置,但这似乎不是真的

问题描述

从下面的代码中可以看出,循环的每次迭代都定义了它自己的实例,所以当每个循环Foo都有一个新的循环时,我看不出它是如何在“循环的前一次迭代”中“移动”的。Foo

如何使错误消失?

fn main() {
    for i in 0..2 {
        let vector: Foo;
        //  ------ move occurs because `vector` has type `Foo`, which does not implement the `Copy` trait
        if i == 0 {
            vector = Foo::Bar(vec![1_f32]);
        } else if i == 1 {
            vector = Foo::Baz(vec![1_u16]);
        }
    //  - value moved here, in previous iteration of loop
        println!("{}", vector.len());
        //             ^^^^^^ value used here after move
    }
}

enum Foo {
    Bar(Vec<f32>),
    Baz(Vec<u16>)
}

impl Foo {
    pub fn len(self) -> usize {
        match self {
            Foo::Bar(vector) => vector.len(),
            Foo::Baz(vector) => vector.len(),
            #[allow(unreachable_patterns)]
            _ => unreachable!()
        }
    }
}

标签: rustmove-semantics

解决方案


通过使用match声明,我设法使错误消失。我不知道为什么会这样,而之前的代码没有:

fn main() {
    for i in 0..2 {
        let vector: Foo = match i {
            0 => Foo::Bar(vec![1_f32]),
            1 => Foo::Baz(vec![1_u16]),
            _ => unreachable!()
        };
        println!("{}", vector.len());
    }
}

推荐阅读