'#[derive(Debug)]'在Rust中究竟是什么意思?

Ama*_*ani 12 rust

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

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

use*_*968 20

#[...]是一个属性struct Person.derive(Debug)要求编译器自动生成一个合适的Debugtrait 实现,它提供{:?}类似的结果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()
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

你的代码.由于这种实现几乎适用于所有用途,因此derive可以免于手动编写.

'a限定了寿命.该字段name是对某些人的参考str; 编译器需要一些关于此引用有效期的信息(最终目标是引用strPerson仍在范围内时不会变为无效).示例中的语法表明Personname共享相同的生命周期a.