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 }
adverb. in an exact manner; accurately or precisely. in every respect; just. it is exactly what I want.
You use exactly with a question to show that you disapprove of what the person you are talking to is doing or saying. What exactly do you mean?
Exactly is an adverb; it modifies a verb. Your first example, "What exactly is..." would be the correct form. The second is more informal; "Exactly what is..." has moved "exactly" away from the verb it is modifying.
#[...]
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With