Skip to content

Slice syntax and &mut operator #55520

Closed
Closed
@cramertj

Description

@cramertj
fn mut_iter(_: &mut dyn Iterator<Item=u8>) {}

fn main() {
    let v = vec![1, 2, 3];
    mut_iter(&mut v.iter().cloned()); // this compiles fine
    mut_iter(&mut v[..].iter().cloned()); // this does not
    mut_iter(&mut (&v[..]).iter().cloned()); // this also compiles fine
}

gives this error:

error[E0596]: cannot borrow `v` as mutable, as it is not declared as mutable
 --> src/main.rs:6:19
  |
4 |     let v = vec![1, 2, 3];
  |         - help: consider changing this to be mutable: `mut v`
5 |     mut_iter(&mut v.iter().cloned());
6 |     mut_iter(&mut v[..].iter().cloned());
  |                   ^ cannot borrow as mutable

error: aborting due to previous error

In both cases, the only thing being mutably referenced is the iterator, not the vec or the slice itself. It's clear that the &mut is binding loosely to the whole remainder of the expression (as it should) because mut_iter is accepting a mutable reference as an argument, so there's no chance this is being parsed as (&mut v[..])....

What's going on here? Repros on both stable and nightly (with and without NLL, which means it's not just funkiness in AST borrowck, right?).

Metadata

Metadata

Assignees

No one assigned

    Labels

    T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions