Open
Description
Code
struct Bar();
impl Bar {
fn mutate(&mut self) {}
}
struct Foo(Bar);
fn f() -> Option<Foo> {
None
}
fn main() {
while let Some(x) = f() {
let y = match x {
Foo(ref bar) => {
bar
}
};
y.mutate()
}
}
Current output
Compiling playground v0.0.1 (/playground)
error[E0596]: cannot borrow `*y` as mutable, as it is behind a `&` reference
--> src/main.rs:20:9
|
20 | y.mutate()
| ^ `y` is a `&` reference, so the data it refers to cannot be borrowed as mutable
|
help: consider annotating `Bar` with `#[derive(Clone)]`
|
1 + #[derive(Clone)]
2 | struct Bar();
|
help: consider specifying this binding's type
|
15 | let y: &mut Bar = match x {
| ++++++++++
For more information about this error, try `rustc --explain E0596`.
error: could not compile `playground` (bin "playground") due to 1 previous error
Desired output
help: consider changing this to be mutable
|
16 | Foo(ref mut bar) => {
| +++
Rationale and extra context
If you make rustc's first suggested change, you still get the same error, and if you make the second, you just end up with this error after:
error[E0308]: mismatched types
--> src/main.rs:17:17
|
17 | bar
| ^^^ types differ in mutability
|
= note: expected mutable reference `&mut Bar`
found reference `&Bar`
Which wasn't really any help at all. With my alternative suggested change, you'll still get one more error, but that one will suggest changing Some(x)
to Some(mut x)
, and that will make it work.
Other cases
Rust Version
Tested on the Rust Playground with both stable 1.83.0 and 1.85.0-nightly 2024-12-04 acabb52 (sorry for the lack of the exact command you wanted, but see rust-lang/rust-playground#1043)
Anything else?
No response