Skip to content

Invalid suggestion to change &self to &mut self in trait implementation #68049

Closed
@phil-opp

Description

@phil-opp

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`A-trait-systemArea: Trait systemC-bugCategory: This is a bug.D-invalid-suggestionDiagnostics: A structured suggestion resulting in incorrect code.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