本文介绍了'let x = x' 在 Rust 中有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在野外看到了这段代码:

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

let fields = fields; 行有什么作用?为什么会在那里?

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

推荐答案

它使 fields 再次不可变.

fields 之前被定义为可变的 (let mut fields = …;),与 sort_by_key 一起使用要求目标是可变的.作者选择这里是为了明确防止进一步的可变性.

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.

将可变绑定降级"为不可变绑定在 Rust 中很常见.

"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
};

这篇关于'let x = x' 在 Rust 中有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 19:11
查看更多