【问题标题】:What exactly does '#[derive(Debug)]' mean in Rust?'#[derive(Debug)]' 在 Rust 中到底是什么意思?
【发布时间】:2017-09-24 09:01:15
【问题描述】:

#[derive(Debug)] 到底是什么意思?跟'a有关系吗?例如:

#[derive(Debug)]
struct Person<'a> {
    name: &'a str,
    age: u8
}

【问题讨论】:

标签: rust


【解决方案1】:

#[...] 是attribute 上的struct Person。 derive(Debug) 要求编译器为auto-generate 提供Debug 特征的合适实现,它以format!("Would the real {:?} please stand up!", Person { name: "John", age: 8 }); 之类的形式提供{:?} 的结果。

你可以通过执行cargo +nightly rustc -- -Zunstable-options --pretty=expanded来查看编译器做了什么。在您的示例中,编译器将添加类似

#[automatically_derived]
#[allow(unused_qualifications)]
impl <'a> ::std::fmt::Debug for Person<'a> {
    fn fmt(&self, __arg_0: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
        match *self {
            Person { name: ref __self_0_0, age: ref __self_0_1 } => {
                let mut builder = __arg_0.debug_struct("Person");
                let _ = builder.field("name", &&(*__self_0_0));
                let _ = builder.field("age", &&(*__self_0_1));
                builder.finish()
            }
        }
    }
}

到您的代码。由于这样的实现几乎适用于所有用途,derive 让您不必手动编写它。

'a 是lifetime 类型的Person 参数;也就是说,(可能)有多个版本的Person,每个版本都有自己的具体生命周期,将命名为'a。此生命周期参数用于限定(通常)字段name 中的引用,即对str 类型的某个值的引用。这是必要的,因为编译器需要一些关于此引用有效时间的信息(最终目标是在 Person 类型的值仍在使用时,对 name 值的引用不会变得无效) .

【讨论】:

  • 为什么年龄不需要生命周期说明符,为什么编译器会生成&amp;&amp;(*__self_0_0)之类的代码? “&&”的意义何在?为什么要在括号内取消引用它?
猜你喜欢
  • 1970-01-01
  • 2022-10-02
  • 2020-05-09
  • 2016-06-12
  • 2020-06-20
  • 2017-08-07
  • 2017-07-20
  • 2014-09-23
相关资源
最近更新 更多