Don't like `<_>`? Avoid it with this one weird trick!

Disclaimer: As you can probably tell from the topic choice, this is probably not actually something you should use. It does work though, so is presented for fun as some features you might not have thought of combining.

You're probably used to colons and underscores to get a Vec from collect, something like one of these

let v: Vec<_> = (1..10).collect();
let v = (1..10).collect::<Vec<_>>();

But did you know you don't need them? You can do it like this too!

let v @ Vec { .. } = (1..10).collect();

Try it out on the playground!


† Or maybe you just use .collect_vec() from itertools.

29 Likes

If you want to level up your Rust game even more, just write code that doesn't need type annotations.

struct Collection {
    numbers: Vec<usize>,
}

fn main() {
    let numbers = (0..10).collect();
    let foo = Collection { numbers };
}

(playground)

3 Likes

Or maybe let v = Vec::from_iter(1..10);

10 Likes

Thanks for sharing this, I always forget that you can write this even if you don't have access to the fields :smile:

I'm having a love/hate relationship with it

3 Likes

Notice that the variable name and the Collection field name must match for this style. Other than that detail, I find this style to be highly readable and would recommend using it.

This feels a bit unfair to me, because your newtype needs a type name, for the constructor.
Note that I generally agree with the sentiment.

Not really.

In that example I had to declare a custom type because the original snippet didn't have any context, but in the real world it's not uncommon to be passing your collection to existing types or functions.

Yes, I agree. Still, your example does not support this IMHO. I'm just unhappy with the example as given.

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.