It is not possible to specify sufficient type information about _; type annotations or general required parameter

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: it is impossible to get enough information about type <<21>; annotation type or general required parameter.

I understand why the compiler complains, but cannot figure out how to do this without assigning type T in the case of F1.

+4
source share
1 answer

Enum variants do not have their own type. There is only a type of enumeration itself. Check out this example:

enum Thing<T> {
    One,
    Two(T),
}

fn main() {
    let a = Thing::One;
    let b = Thing::Two(true);
}

Type bis this Thing<bool>. Type does not mention Two. The same thing should happen for a, but there is nothing that the compiler could use to output the value T, so you must explicitly specify it:

let a = Thing::One::<u8>;

- , - Option:

fn main() {
    // let a = None;
    let a = None::<u8>;
    let b = Some(true);
}

T, .

. max ( , ):

enum Foo {
    One(u64),
    Two(u8),
}

fn main() {
    println!("{}", std::mem::size_of::<u64>());
    // 8
    println!("{}", std::mem::size_of::<u8>());
    // 1
    println!("{}", std::mem::size_of::<Foo>());
    // 16
}

, :

fn main() {
    let a = Some(true);
    let b = None::<bool>;

    println!("{}", std::mem::size_of_val(&a));
    // 2
    println!("{}", std::mem::size_of_val(&b));
    // 2
}

, None :

fn main() {
    let a = None::<u8>;
    println!("{}", std::mem::size_of_val(&a));
    // 2

    let b = None::<u64>;
    println!("{}", std::mem::size_of_val(&b));
    // 16
}

, , None. .

+7

Source: https://habr.com/ru/post/1617993/


All Articles