为枚举实现fmt :: Display - 无法移出借来的内容

时间:2017-01-19 20:39:29

标签: rust

我尝试为fmt::Display实施enum,但我很难理解参考文献:

use std::fmt;

enum Car {
    BMW,
    Ford,
    TopSpeed(i32),
    Specs { weight: i32, name: String },
}

impl fmt::Display for Car {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            &Car::BMW => write!(f, "[Car] BMW"),
            &Car::Ford => write!(f, "[Car] Ford"),
            &Car::TopSpeed(i) => write!(f, "[Car] TopSpeed={}", i),
            &Car::Specs { weight, name } => write!(f, "[Car] Weight={}, Name={}", weight, name),
        }
    }
}

fn main() {
    println!("This is a {}", Car::BMW);
    println!("This is a {}", Car::Ford);
    println!("This is a {}", Car::TopSpeed(200));
    println!("This is a {}",
             Car::Specs {
                 weight: 2000,
                 name: "Clio".to_owned(),
             });
}

收到错误:

error[E0507]: cannot move out of borrowed content
  --> src/main.rs:16:13
   |
16 |             &Car::Specs { weight, name } => write!(f, "[Car] Weight={}, Name={}", weight, name),
   |             ^^^^^^^^^^^^^^^^^^^^^^----^^
   |             |                     |
   |             |                     hint: to prevent move, use `ref name` or `ref mut name`
   |             cannot move out of borrowed content

如果我按照编译器的建议更改为ref name

&Car::Specs { weight, ref name } => write!(f, "[Car] Weight={}, Name={}", weight, name),

有效。为什么我需要将name标记为ref

0 个答案:

没有答案