rust - 错误说值在循环迭代中移动到先前的位置,但这似乎不是真的
问题描述
从下面的代码中可以看出,循环的每次迭代都定义了它自己的实例,所以当每个循环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!()
}
}
}
解决方案
通过使用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());
}
}
推荐阅读
- android - How to change release variant to debug variant?
- python-3.x - 除了默认的两个之外,如何使用 python-pptx 为形状添加额外的渐变填充停止
- c - C中的复数语法错误(使用VScode)
- android - 启动模拟器后,Android Studio Design 预览停止工作
- java - setOnClickListener 抛出空指针异常
- javascript - 如何修复“ctx.clearRect 不是函数”
- java - KStream-KStream 内连接抛出 java.lang.ClassCastException
- php - 错误运行 c:/bitmani/wordpress/php/php -v child 杀死了未知信号
- javascript - 如何在 Node.js 中按顺序发送多个 http 请求?
- swift - 为什么使用 JSONDecoder.decode 方法时没有调用 Decodable 的 init 方法?