Skip to content

Invalid suggestion to introduce as_ref() for Option used in a place expression #99426

Closed
@nagisa

Description

@nagisa

Consider the following code

struct Foo {
    val: i32
}

fn func1() {
    let mut foo = Some(Foo{val: 0});
    let ptr = &mut foo;
    ptr.unwrap().val += 1;
}

Here the diagnostic suggests to add as_ref as such:

note: this function takes ownership of the receiver `self`, which moves `*ptr`
help: consider calling `.as_ref()` to borrow the type's contents
  |
8 |     ptr.as_ref().unwrap().val += 1;
  |         +++++++++

This suggestion is incorrect – as_ref will never (AFAIK) produce a mutable reference necessary for the assignment. We should suggest as_mut where we know that a mutable reference will be required, instead.

Metadata

Metadata

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsD-papercutDiagnostics: An error or lint that needs small tweaks.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions