trait Bar {
fn bar(&self);
}
enum Foo<T: Bar> {
F1,
F2(T)
}
struct Something;
impl Bar for Something {
fn bar(&self) {
}
}
fn main() {
let a = Foo::F2(Something); //<== this works fine.
let b = Foo::F1; //<== gives a compilation error.
}
Compilation error E0282: Unable to infer enough type information about _
; type annotations or generic parameter binding required.
I understand why the compiler is complaining but can't seem to figure out how to do this without having to assign a type to T in the F1 case.
Enum variants do not have their own type. There is only the type of the enum itself. Check out this example:
The type of
b
is aThing<bool>
. The type has no mention ofTwo
. The same thing needs to happen fora
, but there's nothing that the compiler can use to infer the value ofT
, so you have to provide it explicitly:And an even-smaller example is to use an enum that is built-in and very familiar —
Option
:Let's dive in a bit deeper. An enum takes up the space of the max of all the variants (plus a wee bit to tell them apart):
Also, all variants of the same enum take up the same amount of space:
This helps lead us to the realization that not all
None
s are the same:Thus it is important to know exactly what kind of
None
you have. This extends to every kind of enum and variant.