Why can't Rust infer the type of a returned variable?

⚓ Rust    📅 2026-06-07    👤 surdeus    👁️ 3      

surdeus

Consider the following example

#[derive(Debug)]
struct Struct([usize; 10]);

impl Struct {
    pub fn new(slice: &[usize]) -> Self {
        let mut array = slice.try_into().expect("not enough elements in data");
        array.sort();
        Self(array)
    }
}

Playground

The Rust compiler complains that that "type annotations needed" (E0282) on the declaration of variable array. It seems to me that Rust should be able to unambiguously infer the type of array:

  • The return value is known to be of type Struct because of -> Self in the new signature
  • This return value is expressed as Self(array) in the function body.
  • Therefore array must be of type [usize; 10] because no other type satisfies the struct definition for field 0 which is explicitly defined as [usize; 10] in the struct definition for Struct

I'm confused as to why the Rust compiler can't figure this out and insists on type annotations in the declaration of variable array. What's more perplexing, is that if I remove the call to [T]::sort like so:

impl Struct {
    pub fn new(slice: &[usize]) -> Struct {
        let array = slice.try_into().expect("not enough elements in data");
        Self(array)
    }
}

The compiler seemingly has no problem inferring that variable array is of type [usize; 10], presumably using the logic I listed above. Why is it that the introduction of the call to [T]::sort suddenly ambiguates the type of array?

3 posts - 3 participants

Read full topic

🏷️ Rust_feed