[英]Assigning value of vector inside match: move occurs … which does not implement the `Copy` trait
For convenience, you can find the below code on Rust Playground :为方便起见,您可以在Rust Playground上找到以下代码:
fn main() {
println!("Hello, world!");
let n = 5;
let mut my_vector : Vec<u16>;
loop {
let x: Result<i32, &str> = Ok(-3);
match x {
Ok(-3) => {
my_vector = (0..n).map(|x| x).collect();
// works
for e in my_vector {
println!("{}", e);
}
},
Err(e) => {
eprintln!("couldn't recieve a datagram: {}", e);
},
_ => {
}
}
// does not work
for e in my_vector {
println!("{}", e);
}
break;
}
}
I get the error " move occurs because my_vector has type Vec<u16>, which does not implement the Copy trait
" and I am not able to make the program compile (and work), any help very well appreciated!我收到错误“
move occurs because my_vector has type Vec<u16>, which does not implement the Copy trait
”,并且我无法使程序编译(和工作),非常感谢任何帮助!
NB: This is a simplified example of the error I am facing in my program.注意:这是我在程序中遇到的错误的简化示例。
How could I set the value of the vector inside the match {} and then reuse it later on?如何在 match {} 中设置向量的值,然后再使用它?
for e in my_vector {
println!("{}", e);
}
This consumes my_vector
.这会消耗
my_vector
。 If you want to iterate the elements and still be able to use them later, you can use .iter()
如果你想迭代元素并且以后仍然可以使用它们,你可以使用
.iter()
for e in my_vector.iter() {
println!("{}", e);
}
Here's a working playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=8c99592ef98735472165f76b6ceb9b19这是一个工作场所: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=8c99592ef98735472165f76b6ceb9b19
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.