By timthelion


2019-02-08 15:13:54 8 Comments

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?

2 comments

@mcarton 2019-02-08 15:19:33

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

@Synesso 2019-02-09 03:06:00

Or "upgrading", depending upon your perspective.

@Darth Boiethios 2019-02-13 08:48:35

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.

@Govind Parmar 2019-02-08 15:18:18

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

Related Questions

Sponsored Content

7 Answered Questions

[SOLVED] What are the differences between Rust's `String` and `str`?

  • 2014-06-11 08:29:34
  • Daniel Fath
  • 28945 View
  • 247 Score
  • 7 Answer
  • Tags:   string rust

2 Answered Questions

[SOLVED] What is the r#""# operator in Rust?

  • 2014-10-28 15:04:35
  • アレックス
  • 11122 View
  • 36 Score
  • 2 Answer
  • Tags:   string syntax rust

0 Answered Questions

What does () mean in Rust?

  • 2018-11-19 03:38:09
  • stacksonstacks
  • 118 View
  • 3 Score
  • 0 Answer
  • Tags:   rust

3 Answered Questions

[SOLVED] What does Rust have instead of a garbage collector?

  • 2015-09-20 08:37:31
  • rix
  • 24131 View
  • 65 Score
  • 3 Answer
  • Tags:   rust

2 Answered Questions

[SOLVED] Does Rust 2018 support "if let" chaining?

  • 2018-11-10 02:17:55
  • Michael Anderson
  • 220 View
  • 6 Score
  • 2 Answer
  • Tags:   rust

1 Answered Questions

[SOLVED] What is the ..= (dot dot equals) operator in Rust?

2 Answered Questions

[SOLVED] immutability of rust let bindings

1 Answered Questions

[SOLVED] How does Rust handle functions with "..." at the end of args?

  • 2016-08-17 21:28:11
  • user1244932
  • 152 View
  • 3 Score
  • 1 Answer
  • Tags:   rust

1 Answered Questions

[SOLVED] What does it mean to instantiate a Rust generic with an underscore?

  • 2016-05-13 17:11:39
  • Zephilim
  • 1722 View
  • 5 Score
  • 1 Answer
  • Tags:   generics rust

3 Answered Questions

[SOLVED] Why does Rust bother with "let"?

  • 2015-08-24 11:01:03
  • user3728501
  • 1984 View
  • 7 Score
  • 3 Answer
  • Tags:   rust

Sponsored Content