Does the magic have a name <Trait>::<fn>() ex Default::default()


I just came across as I'm learning the use of Default::default(), as used like this assert_eq!(SomeEnum::Empty, Default::default()); and in the docs like this let x: SomeStruct = Default::default();. This is throwing me as by looking I can't reason about the behavior. I understand the magic or automatic behavior, but nothing signals it other than obvious name, Default, in the syntax.

Does this have a name?
Is it used anywhere else other than Default::default()?

I've seen trait bounds and trait impls and so on. Had not seen a traits impl fn called in this way until now. Thanks for the help.

Default is a trait that you implement to define some good default values.

You can view it as an abbreviated form of fully-qualified syntax.

let _ = <String as Default>::default();
let _: String = <_ as Default>::default();
let _: String = <_>::default();
let _: String = Default::default();

It's not Default specific (but more common for trait functions that don't have self receivers for obvious reasons).


Thanks for replying, I do understand that. Not really my question though, does this "pattern" have a name, example ::<> has a name turbo fish and it has a behavior it defines. However the compiler magic is hard to reason about just from the syntax.

Thank you. Wow, that now clears it up. Especially the note about self receivers. Aha! Thank you

There is no magic. Default is a trait and Default::default() is a trait method. Since its return type is Self, annotating the return type with a concrete type makes type inference infer that Self == ThatConcreteType, and looks up its Default impl.

1 Like

Thanks, I am not a person in the know, but your reply seems to fit; However, for me it is not as clear as the fully qualified syntax especially the doc page wording. Especially the note about sugar. Coming from OOP the sugar gave me a different impression vs what the compiler is actually allowing and doing.

The docs don't seem to have caught up, unless I missed it. as has an additional use in fully qualified syntax or Disambiguating Function Calls as I have learned.

as type cast reference

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.