Inconsistency with Vec<_>?

The following code runs fine in Rust Playground:

pub fn main() {
    let (x1, y1, x2, y2) = (29.0, 29.0, 86.0, 0.0);
    let num_i32 = 5i32;

    let mut tuple_vec2: Vec<_> = Vec::new();
    tuple_vec2.push((x1, y1, num_i32, "a1"));
    tuple_vec2.push((x2, y2, num_i32, "h1"));

    for x in tuple_vec2.iter() {
        println!("{:?}", x);
    }
}

But when I shorten the code like this:

pub fn main() {
    let (x1, y1, x2, y2) = (29.0, 29.0, 86.0, 0.0);
    let num_i32 = 5i32;

    let mut tuple_vec2: Vec<_> = Vec::new();
    // tuple_vec2.push((x1, y1, num_i32, "a1"));
    // tuple_vec2.push((x2, y2, num_i32, "h1"));

    // for x in tuple_vec2.iter() {
    //     println!("{:?}", x);
    // }
}

it gives error:

 Compiling playground v0.0.1 (/playground)
error[E0282]: type annotations needed for `std::vec::Vec<_>`
 --> src/main.rs:5:25
  |
5 |     let mut tuple_vec2: Vec<_> = Vec::new();
  |         --------------  ^^^^^^ cannot infer type
  |         |
  |         consider giving `tuple_vec2` the explicit type `std::vec::Vec<_>`, with the type parameters specified

error: aborting due to previous error

I'd like to have the vector so I can pass it to a function to be populated with tuples that contain different types of data in them.
What's the right syntax here?

Vec<({float}, {float}, i32, &'static str)>

A cool trick you can do (which I do when I'm feeling lazy), is give some bogus type and let the compiler tell you the correct type:

pub fn main() {
    let (x1, y1, x2, y2) = (29.0, 29.0, 86.0, 0.0);
    let num_i32 = 5i32;

    let mut tuple_vec2: Vec<u32> = Vec::new();
    tuple_vec2.push((x1, y1, num_i32, "a1"));
    tuple_vec2.push((x2, y2, num_i32, "h1"));

    for x in tuple_vec2.iter() {
        println!("{:?}", x);
    }
}

Have you tried passing it? If you pass the vec into a function, the compiler can usually infer what it needs to be. You can't just create a vec in incomplete code without an inferrable type...

pub fn main() {
    let (x1, y1, x2, y2) = (29.0, 29.0, 86.0, 0.0);
    let num_i32 = 5i32;

    let mut tuple_vec2: Vec<_> = Vec::new();
    take_vec(tuple_vec2);
}

fn take_vec(v: Vec<(f32, f32, i32, &'static str)>) { unimplemented!() }

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.