Faulty compiler suggestion on immutable loop variable

⚓ Rust    📅 2026-03-20    👤 surdeus    👁️ 2      

surdeus

I just stumbled over this while implementing selection sort on the playground:

fn selection_sort<T>(lst: &mut [T]) where T: Ord {
    for i in 0..lst.len() {
        for j in (i+1)..lst.len() {
            if lst[j] < lst[i] {
                i = j;
            }
        }
    }
}
  Compiling playground v0.0.1 (/playground)
error[E0384]: cannot assign twice to immutable variable `i`
 --> src/lib.rs:5:17
  |
2 |     for i in 0..lst.len() {
  |         - first assignment to `i`
...
5 |                 i = j;
  |                 ^^^^^ cannot assign twice to immutable variable
  |
help: consider making this binding mutable
  |
2 |     for (mut i) i in 0..lst.len() {
  |         +++++++

For more information about this error, try `rustc --explain E0384`.
error: could not compile `playground` (lib) due to 1 previous error

This is obviously invalid syntax:

fn selection_sort<T>(lst: &mut [T]) where T: Ord {
    for (mut i) i in 0..lst.len() {
        for j in (i+1)..lst.len() {
            if lst[j] < lst[i] {
                i = j;
            }
        }
    }
}
   Compiling playground v0.0.1 (/playground)
error: missing `in` in `for` loop
 --> src/lib.rs:2:16
  |
2 |     for (mut i) i in 0..lst.len() {
  |                ^
  |
help: try adding `in` here
  |
2 |     for (mut i) in i in 0..lst.len() {
  |                 ++

error: expected `{`, found keyword `in`
 --> src/lib.rs:2:19
  |
2 |     for (mut i) i in 0..lst.len() {
  |                   ^^ expected `{`

error: could not compile `playground` (lib) due to 2 previous errors

Imho the error message for the original code should look like:

   Compiling playground v0.0.1 (/playground)
error[E0384]: cannot assign twice to immutable variable `i`
 --> src/lib.rs:5:17
  |
2 |     for i in 0..lst.len() {
  |         - first assignment to `i`
...
5 |                 i = j;
  |                 ^^^^^ cannot assign twice to immutable variable
  |
help: consider making this binding mutable
  |
2 |     for mut i in 0..lst.len() {
  |         ++++

For more information about this error, try `rustc --explain E0384`.
error: could not compile `playground` (lib) due to 1 previous error

Is this a known error?

2 posts - 2 participants

Read full topic

🏷️ Rust_feed