Description
Summary: The compiler suggests changing &self
to &mut self
when trying to modify self
in a method. For trait implemantions this does not work because it would require changing the trait definition too (which is often not possible).
Example:
I was trying to implement the GlobalAllocator
trait from the standard library for a custom type:
use std::alloc::{GlobalAlloc, Layout};
struct Test(u32);
unsafe impl GlobalAlloc for Test {
unsafe fn alloc(&self, _layout: Layout) -> *mut u8 {
self.0 += 1;
0 as *mut u8
}
unsafe fn dealloc(&self, _ptr: *mut u8, _layout: Layout) {
unimplemented!();
}
}
This of course doesn't work since you can't modify data behind a &self
reference:
error[E0594]: cannot assign to `self.0` which is behind a `&` reference
--> src/main.rs:7:9
|
6 | unsafe fn alloc(&self, _layout: Layout) -> *mut u8 {
| ----- help: consider changing this to be a mutable reference: `&mut self`
7 | self.0 += 1;
| ^^^^^^^^^^^ `self` is a `&` reference, so the data it refers to cannot be written
However, I noticed that the help message suggests changing the &self
to &mut self
, which is incorrect since that would require changing the trait definition in the standard library too.
Suggestion: I don't know if this is possible, but maybe this help message should only be shown for "normal" methods and hidden when implementing trait methods?