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

和平:

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

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

#[...]是一个属性struct Personderive(Debug)要求编译器自动生成Debug trait 的合适实现,以提供{:?}类似的结果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限定了寿命该领域name是对一些事物的参考str; 编译器需要一些有关此引用将有效多长时间的信息(以达到对该引用仍然在范围内str不会变为无效的最终目标Person)。您的示例中的语法指出Personname具有相同的生存期a

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章