[英]How pattern matching in Rust works with `let` statement
为什么片段pattern_matching_2
和pattern_matching_3
有效,而pattern_matching_1
无效? 编译器建议let &x = &foo
移动字符串 hello,我知道这一点并且看不到问题出在哪里——无论如何我都没有使用foo
,编译器不会抱怨pattern_matching_3
,它移动字符串 hello 也是如此。
示例片段改编自这个答案,它没有回答我的问题。
代码片段:
fn pattern_matching_1() {
let foo = String::from("hello");
let &x = &foo;
println!("{}", x);
}
fn pattern_matching_2() {
let foo = 12;
let &x = &foo;
println!("{}", x);
}
fn pattern_matching_3() {
let foo = String::from("hello");
let x = foo;
println!("{}", x);
}
pattern_matching_1
的编译器错误:
error[E0507]: cannot move out of a shared reference
--> src/main.rs:26:14
|
26 | let &x = &foo;
| -- ^^^^
| ||
| |data moved here
| |move occurs because `x` has type `String`, which does not implement the `Copy` trait
| help: consider removing the `&`: `x`
他的编译器建议
let &x = &foo
移动字符串 hello,我知道并且看不到问题出在哪里
问题是您给编译器一个对变量 ( &foo
) 的不可变引用,然后要求它移走底层数据。 这不是不可变引用所允许的操作。
为了更明确,将移出部分提取到另一个 function 中:
fn pattern_matching_1_helper(r: &String) {
let &x = r;
println!("{}", x);
}
fn pattern_matching_1() {
let foo = String::from("hello");
pattern_matching_1_helper(&foo);
}
我希望很明显pattern_matching_1_helper
不能自行编译。 但是您代码中的组合版本确实没有什么不同。
pattern_matching_2
编译因为i32
是Copy
,所以编译器不需要移动。
fn pattern_matching_3() {
let foo = String::from("hello");
let x = foo;
println!("{}", x);
}
这是有效的,因为foo
被移动到x
中,所以foo
不再是一个可用的变量。 可以从拥有它的变量中移动数据,只要该变量不再使用。
fn pattern_matching_1() {
let foo = String::from("hello");
let &x = &foo;
println!("{}", x);
}
这不起作用,因为foo
仍然是字符串的所有者,但您正试图将数据移出x
,而 x 只是借用了它。
pattern_matching_2
有效,因为i32
是Copy
,所以没有移动。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.