E0282 - Error codes index
Description: Book listing all Rust error codes

## Keyboard shortcuts

Press `←` or `→` to navigate between chapters

Press `S` or `/` to search in the book

Press `?` to show this help

Press `Esc` to hide this help

# Error code E0282

The compiler could not infer a type and asked for a type annotation.

Erroneous code example:

    #![allow(unused)]
    fn main() {
    let x = Vec::new();
    }

This error indicates that type inference did not result in one unique possible type, and extra information is required. In most cases this can be provided by adding a type annotation. Sometimes you need to specify a generic type parameter manually.

In the example above, type `Vec` has a type parameter `T`. When calling `Vec::new`, barring any other later usage of the variable `x` that allows the compiler to infer what type `T` is, the compiler needs to be told what it is.

The type can be specified on the variable:

    #![allow(unused)]
    fn main() {
    let x: Vec<i32> = Vec::new();
    }

The type can also be specified in the path of the expression:

    #![allow(unused)]
    fn main() {
    let x = Vec::<i32>::new();
    }

In cases with more complex types, it is not necessary to annotate the full type. Once the ambiguity is resolved, the compiler can infer the rest:

    #![allow(unused)]
    fn main() {
    let x: Vec<_> = "hello".chars().rev().collect();
    }

Another way to provide the compiler with enough information, is to specify the generic type parameter:

    #![allow(unused)]
    fn main() {
    let x = "hello".chars().rev().collect::<Vec<char>>();
    }

Again, you need not specify the full type if the compiler can infer it:

    #![allow(unused)]
    fn main() {
    let x = "hello".chars().rev().collect::<Vec<_>>();
    }

Apart from a method or function with a generic type parameter, this error can occur when a type parameter of a struct or trait cannot be inferred. In that case it is not always possible to use a type annotation, because all candidates have the same return type. For instance:

    #![allow(unused)]
    fn main() {
    struct Foo<T> {
        num: T,
    }

    impl<T> Foo<T> {
        fn bar() -> i32 {
            0
        }

        fn baz() {
            let number = Foo::bar();
        }
    }
    }

This will fail because the compiler does not know which instance of `Foo` to call `bar` on. Change `Foo::bar()` to `Foo::<T>::bar()` to resolve the error.