Issue
What exactly does #[derive(Debug)]
mean? Does it have something to do with 'a
? For example:
#[derive(Debug)]
struct Person<'a> {
name: &'a str,
age: u8
}
Solution
#[...]
is an attribute on struct Person
. derive(Debug)
asks the compiler to auto-generate a suitable implementation of the Debug
trait, which provides the result of {:?}
in something like format!("Would the real {:?} please stand up!", Person { name: "John", age: 8 });
.
You can see what the compiler did by executing cargo +nightly rustc -- -Zunstable-options --pretty=expanded
. In your example, the compiler will add something like
#[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()
}
}
}
}
to your code. As such an implementation is suitable for almost all uses, the derive
saves you from writing it by hand.
The 'a
is a lifetime-parameter for the type Person
; that is, there (could be) several versions of Person
, each with its own concrete lifetime, which will be named 'a
. This lifetime-parameter is used to qualify (generically) the reference in the field name
, a reference to some value of type str
. This is necessary because the compiler will need some information on how long this reference will be valid (to the ultimate goal that the reference to the value of name
does not become invalid while a value of type Person
is still in use).
Answered By - user2722968 Answer Checked By - Timothy Miller (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.