Rust: Invalid suggestion to change `&self` to `&mut self` in trait implementation

Created on 9 Jan 2020  路  1Comment  路  Source: rust-lang/rust

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!();
    }
}

(playground)

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?

A-diagnostics A-suggestion-diagnostics A-traits C-bug D-invalid-suggestion T-compiler

Most helpful comment

Maybe only hide the suggestion if the trait comes from a foreign crate?

>All comments

Maybe only hide the suggestion if the trait comes from a foreign crate?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

withoutboats picture withoutboats  路  308Comments

nikomatsakis picture nikomatsakis  路  274Comments

nikomatsakis picture nikomatsakis  路  268Comments

alexcrichton picture alexcrichton  路  240Comments

thestinger picture thestinger  路  234Comments