首页 > 解决方案 > 为什么编译器报告部分移动错误而不移动?

问题描述

在下面的程序中,为什么编译器错误提到部分移动而不是仅仅移动?从 x 到 z 的部分移动是如何发生的?如果 &mut T 没有实现 Copy 特征,它应该被移动而不是部分移动?

fn main() {
    let mut y = 2;
    let x = Some(&mut y);
    match x {
        None => (),
        Some(z) => {
        *z = 3; 
        println!("{}", z)},
    };
    println!("{:?}",x);
}

以下是操场上的错误

Compiling playground v0.0.1 (/playground)
error[E0382]: borrow of partially moved value: `x`
  --> src/main.rs:10:21
   |
6  |         Some(z) => {
   |              - value partially moved here
...
10 |     println!("{:?}",x);
   |                     ^ value borrowed here after partial move
   |
   = note: partial move occurs because value has type `&mut i32`, which does not implement the `Copy` trait
help: borrow this field in the pattern to avoid moving `x.0`
   |
6  |         Some(ref z) => {
   |              ^^^

For more information about this error, try `rustc --explain E0382`.
error: could not compile `playground` due to previous error

标签: rust

解决方案


考虑Option枚举:

enum Option<T> {
    Some(T),
    None
}

在该枚举中,Some(T)实际上是一个元组 struct,包含一个字段。

当您使用模式匹配来提取内部 T 的值时,这将是单个字段元组结构的一个字段的部分移动Some

从只有一个字段的结构中部分移动字段可能看起来没有用,但更一般地说,结构中可以有任意数量的字段。

也可以看看:


推荐阅读