1

I have a Vec of structs and I want to get the ones from position x to y:

fn main() {
    #[derive(Debug)]
    struct A {
        name: String,
    }
    
    let x = A { name: "X".to_string() };
    let y = A { name: "Y".to_string() };
    let z = A { name: "Z".to_string() };
    
    let v = vec!(x,y,z);
    
    println!("{:?}", v[0..1]);
}

Here's the Rust Playground link for it.

I'm getting the error:

error[E0277]: the size for values of type `[A]` cannot be known at compilation time
   --> src/main.rs:13:5
    |
13  |     println!("{:?}", v[0..1]);
    |     ^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time

How can I make sure the size is known at compile time? I couldn't find any obvious answer, therefore I think I'm missing something fundamental.

pretzelhammer
  • 13,874
  • 15
  • 47
  • 98
ohboy21
  • 4,259
  • 8
  • 38
  • 66

1 Answers1

4

Change

println!("{:?}", v[0..1]);

To

println!("{:?}", &v[0..1]);

Indexing a Vec with a Range returns a slice which is sized, but when you use [] on a variable the compiler automatically dereferences the returned value (it's just syntax sugar), which in this case makes the slice unsized, so you have to put a reference in front of it to make it sized again.

See also:

pretzelhammer
  • 13,874
  • 15
  • 47
  • 98