136

I saw this code in the wild:

fields.sort_by_key(|&(_, ref field)| field.tags().into_iter().min().unwrap());
let fields = fields;

What does the let fields = fields; line do? Why is it there?

0

2 Answers 2

178

It makes fields immutable again.

fields was previously defined as mutable (let mut fields = …;), to be used with sort_by_key which sorts in-place and requires the target to be mutable. The author has chosen here to explicitly prevent further mutability.

"Downgrading" a mutable binding to immutable is quite common in Rust.

Another common way to do this is to use a block expression:

let fields = {
    let mut fields = …;
    fields.sort_by_key(…);
    fields
};
7
  • 53
    Or "upgrading", depending upon your perspective.
    – Synesso
    Commented Feb 9, 2019 at 3:06
  • 10
    IMO your another way to write that is the way to go: the mutable variable is scoped the time we need to use it, and then it is moved. It is better semantically.
    – Boiethios
    Commented Feb 13, 2019 at 8:48
  • 1
    @iago-lito Honestly, I'm not sure, but my uneducated guess is that is does not change anything.
    – Boiethios
    Commented Feb 27, 2019 at 19:47
  • 1
    @iago-lito Right now it actually does! However this is considered a bug and is likely to be fixed at some point.
    – mcarton
    Commented Feb 27, 2019 at 20:13
  • 2
    @iago-lito A recent comment on the issue suggests that nowadays both examples generate the same code.
    – mcarton
    Commented Oct 2, 2022 at 20:34
21

The statement let var = var; makes var immutable and bound to its current value. fields was declared as mut earlier.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.