What does 'let x = x' do in Rust?

后端 未结 2 538
走了就别回头了
走了就别回头了 2020-11-30 03:36

I saw this code in the wild:

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

What d

相关标签:
2条回答
  • 2020-11-30 04:02

    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
    };
    
    0 讨论(0)
  • 2020-11-30 04:07

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

    0 讨论(0)
提交回复
热议问题