'#[derive(Debug)]' Rust 中到底是什么意思?



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

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

#[...]struct Person上的属性。derive(Debug)要求编译器自动生成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是类型Person的寿命参数;也就是说,(可能有)Person的几个版本,每个版本都有自己的具体寿命,将命名为'a。此寿命参数用于(一般)在字段name中的参考,这是对类型str的某些值的引用。这是必要的,因为编译器将需要一些有关此引用有效多长时间的信息(对于最终目标,即name值的引用在使用类型Person的值时不会变得无效)。

最新更新