rust - Rust 中的模式匹配如何与 `let` 语句一起使用
问题描述
为什么片段pattern_matching_2
和pattern_matching_3
工作,而pattern_matching_1
没有?编译器建议let &x = &foo
移动字符串 hello,我知道并且看不到问题出在哪里——foo
反正我没有使用,编译器不会抱怨任何关于pattern_matching_3
hello 的内容,这也会移动字符串 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
) 的不可变引用,然后要求它移走底层数据。这不是不可变引用所允许的操作。
为了使这一点更明确,将移出部分提取到另一个函数中:
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
is Copy
,所以编译器不需要移动。
推荐阅读
- python - python/tkinter 新手,不知道我做错了什么?
- android - Android中的基本测试NavigationController
- flutter - 如何在颤动中使用画布创建宠物爪标志
- sql - 如何将查询结果用作 liquibase defaultValueComputed?
- python - 你能在 Python 中预编译正则表达式,将它们保存到文件中,然后从文件中重新加载它们吗?
- python - Python - 解析 Junos 路由器配置以连续显示数据
- installation - 无法执行 /usr/local/bin/pip3:权限被拒绝
- javascript - 显示来自 firebase 存储的所有图像(反应原生)
- r - 绘制 3D 网络
- python - Conda-pack 破坏了 spyder