Skip to content

Confusing compilation error when forgetting to deref_mut in a chain of iterators #105337

Open
@robinmoussu

Description

@robinmoussu

This doesn’t compile:

fn foo(items: &mut [u8]) -> u8 {
    // The centent of this function isn’t important
    items.sort();
    42
}

fn main() {
    let mut x: Vec<Vec<u8>> = vec![
        vec![0, 1, 2],
        vec![3, 4, 5],
    ];
    let x = x
        .iter_mut()
        .map(foo) // <-- this line
    println!("{:?}", x);
}
error[[E0631]](https://doc.rust-lang.org/stable/error-index.html#E0631): type mismatch in function arguments
  --> src/main.rs:20:14
   |
1  | fn foo(items: &mut [u8]) -> u8 {
   | ------------------------------ found signature defined here
...
20 |         .map(foo);
   |          --- ^^^ expected due to this
   |          |
   |          required by a bound introduced by this call
   |
   = note: expected function signature `fn(&mut Vec<u8>) -> _`
              found function signature `for<'r> fn(&'r mut [u8]) -> _`
note: required by a bound in `map`

For more information about this error, try `rustc --explain E0631`.

The solution is either to call first deref

.map(std::ops::DerefMut::deref_mut).map(foo)

or

.map(|items| items.as_mut())

Or to use a lambda

.map(|mut items| foo(&mut items))

The current error doesn’t help to understand what the issue is and it’s very confusing because it may look like a lifetime error (because of the for<'r>…).

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=c6ac2ca7a31b126442978d30419e07a8

Metadata

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsD-confusingDiagnostics: Confusing error or lint that should be reworked.D-newcomer-roadblockDiagnostics: Confusing error or lint; hard to understand for new users.D-terseDiagnostics: An error or lint that doesn't give enough information about the problem at hand.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