reference - Understanding the Debug implementation for Vec<T> -
trying implement debug trait custom type stumbled upon implementation vec<t>. have difficulties understanding how works.
the implementation goes this:
impl<t: fmt::debug> fmt::debug vec<t> { fn fmt(&self, f: &mut fmt::formatter) -> fmt::result { fmt::debug::fmt(&**self, f) } } i understand calls fmt implementation other type. cannot understand type is. i've tried figure out of another question, , searching among implementations of debug looks appropriate (maybe &[t]), no success.
what exact meaning of &**self in context? implementation of debug being called?
in cases this, find useful make compiler tell type is. cause type error , let compiler diagnostics you. easiest way try assign item of type ():
fn main() { let v = &vec![1,2,3]; let () = v; let () = &**v; } the errors are:
<anon>:3:9: 3:11 error: mismatched types: expected `&collections::vec::vec<_>`, found `()` (expected &-ptr, found ()) [e0308] <anon>:3 let () = v; ^~ <anon>:4:9: 4:11 error: mismatched types: expected `&[_]`, found `()` (expected &-ptr, found ()) [e0308] <anon>:4 let () = &**v; ^~ thus v &collections::vec::vec<_> , &**v &[_].
more detailed, vec has this:
impl<t> deref vec<t> { type target = [t]; // ... } so, dereference once go &vec<t> vec<t>, dereference again [t], , reference once &[t].
[t] has this:
impl<t> debug [t] { fn fmt(&self, ...) ...; } however, when searching appropriate method call, rust automatically attempt dereference target. means can find method on [t] &[t].
as corrected francis gagné, debug::fmt takes &self, directly calling &[t] finds matching implementation. no need automatic referencing or dereferencing.
Comments
Post a Comment