Default generic parameter

I want to wrap values in a struct that adds some logic to it. For instance, I want to have a u64 wrapper that will only allow certain values to be set to it, and that validation is done using a trait.

There is a trait implementation that allows all values (i.e. it rejects none), and it would be neat to make that the "default".

Playground

Uncommenting line 65 makes the code no longer build. I was kind of hoping that the default parameter on line 28 would be the magic sauce to make it work.

Seems like the method-call turbofish is restricted to type inference only; if you move the ascription to the pattern it picks up the default as expected:

    let val: U64Val = Default::default();

Apparently, this also works:

    let val = <U64Val>::default();
2 Likes

unfortunately, that's not how type inference works. a good reading:

3 Likes

:exploding_head:

2 Likes

Here's an exploration of why that works.

4 Likes