rust-lang / rust

Empowering everyone to build reliable and efficient software.
https://www.rust-lang.org
Other
97.25k stars 12.57k forks source link

Better slices array type inference #74626

Open leonardo-m opened 4 years ago

leonardo-m commented 4 years ago

This code:

#[allow(unused_variables)]
fn main() {
    let foos1: [&[u32]; 3] = [&[1_u32, 2, 3], &[1, 2], &[]];
    let foos2 = [&[1_u32, 2, 3], &[1, 2], &[]];
}

Currently (rustc 1.47.0-nightly 8ad7bc3f4 2020-07-21) this gives:

error[E0308]: mismatched types
 --> ...\test.rs:4:34
  |
4 |     let foos2 = [&[1_u32, 2, 3], &[1, 2], &[]];
  |                                  ^^^^^^^ expected an array with a fixed size of 3 elements, found one with 2 elements
  |
  = note:   expected type `&[u32; 3]`
          found reference `&[u32; 2]`

Is it possible to improve the type system so foo2 too compiles?

Alexendoo commented 4 years ago

Much like giving the hint of _u32 to the first element, you can do

    let foos2 = [&[1_u32, 2, 3][..], &[1, 2], &[]];
leonardo-m commented 4 years ago

Thank you, your code compiles, and I'll use it. But I think my original ER issue is still valid.