首页 > 解决方案 > Rust 中的模式匹配如何与 `let` 语句一起使用

问题描述

为什么片段pattern_matching_2pattern_matching_3工作,而pattern_matching_1没有?编译器建议let &x = &foo移动字符串 hello,我知道并且看不到问题出在哪里——foo反正我没有使用,编译器不会抱怨任何关于pattern_matching_3hello 的内容,这也会移动字符串 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`

标签: rust

解决方案


他的编译器建议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编译因为i32is Copy,所以编译器不需要移动。


推荐阅读