Idiomatic to use references like values if they deref?

Say that I have a Vec and I want to create a new Vec from it where each element of the new Vec is two times the element in the first.

let v1 = vec![1.0, 2.0, 3.0];
let v2 = v1.iter().map(|x| *x * 2.0).collect::<Vec<f64>>();

In the map, x is a &64 so I'm using *x to deref to the value. I know that I can omit this explicit dereferencing and Rust will figure it out (i.e. map(|x| x * 2.0)), but I'm wondering if it is considered better to be explicit or if it is more idiomatic to omit these sorts of explicit dereference operators when possible?


For this case, it doesn't matter (as far as "idiomaticity" goes).
For readability, you may want to avoid the explicit dereference.

There really isn't an importance - your code is valid, either way. Rust has a way of forcing you to be explicit when needed - if you have the ability to make your code look simpler, it's probably for the better.

In other cases, such as type casts, Rust makes you be explicit - for the better. It's very easy to mess up while fasting, so if Rust did that under-the-hood, it would lead to error messages of code you didn't write.

In the end, the intent of the code is clear either way, but it's cleaner as an implicit dereference.

I try to avoid them because I think *x * 2.0 looks weird.

One alternative is to write map(|&x| x * 2.0), i.e. using pattern matching to do the dereference instead of *. This only works with real references though, not smart pointers.

1 Like

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.