Search code examples
rusttype-inferencegeneric-programming

Unexpected type inference failure: wrong number of type arguments


In this example, the compiler can not infer the matrix type:

type Mat4x4<T> = [T; 16];

fn main() {
    let m: Mat4x4 = [0.4323f32; 16];
    println!("{:?}", m);
}

The working code is:

type Mat4x4<T> = [T; 16];

fn main() {
    let m: Mat4x4<f32> = [0.4323f32; 16];
    println!("{:?}", m);
}

Is this an expected act?


Solution

  • This is not a type inference issue:

    type Mat4x4<T> = [T; 16];
    
    fn main() {
        let m: Mat4x4 = [0.4323f32; 16];
        println!("{:?}", m);
    }
    

    Yields the following error message:

    error[E0107]: wrong number of type arguments: expected 1, found 0
     --> src/main.rs:4:12
      |
    4 |     let m: Mat4x4 = [0.4323f32; 16];
      |            ^^^^^^ expected 1 type argument
    

    The complaint here is that Mat4x4 is not a type, it's a template or blueprint to create a type.

    An analogy would be that Mat4x4 is a waffle iron, and Mat4x4<f32> is a waffle that comes out of it. If you are served the waffle iron (with maple syrup on top, of course) you will likely be disappointed!

    The same applies here: when you give the compiler the blueprint where it expects the final product, it signals you that it was not what it expected.


    You can supply a dummy argument (_), and it will be inferred:

    let m: Mat4x4<_> = [0.4323f32; 16];