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

What exactly does '#[derive(Debug)]' mean in Rust?

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

1
2
3
4
5
#[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来查看编译器的工作。在您的示例中,编译器将添加类似

的内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#[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的某些值的引用。这是必需的,因为编译器将需要一些有关此引用有效时间的信息(最终目标是,在仍使用类型Person的值时,对name的引用不会变得无效) 。