Remove wrong suggestion part (#983)

This commit is contained in:
HKalbasi
2021-05-17 13:00:11 +04:30
committed by GitHub
parent bf4f881079
commit b070fa8ee6

View File

@@ -172,9 +172,6 @@ Note that we don't perform any bounds checks or alignment adjustments, so this i
error[E0594]: cannot assign to `self.next` which is behind a `&` reference
--> src/allocator/bump.rs:29:9
|
26 | unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
| ----- help: consider changing this to be a mutable reference: `&mut self`
...
29 | self.next = alloc_start + layout.size();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `self` is a `&` reference, so the data it refers to cannot be written
```
@@ -186,8 +183,6 @@ The error occurs because the [`alloc`] and [`dealloc`] methods of the `GlobalAll
[`alloc`]: https://doc.rust-lang.org/alloc/alloc/trait.GlobalAlloc.html#tymethod.alloc
[`dealloc`]: https://doc.rust-lang.org/alloc/alloc/trait.GlobalAlloc.html#tymethod.dealloc
Note that the compiler suggestion to change `&self` to `&mut self` in the method declaration does not work here. The reason is that the method signature is defined by the `GlobalAlloc` trait and can't be changed on the implementation side. (I opened an [issue](https://github.com/rust-lang/rust/issues/68049) in the Rust repository about the invalid suggestion.)
#### `GlobalAlloc` and Mutability
Before we look at a possible solution to this mutability problem, let's try to understand why the `GlobalAlloc` trait methods are defined with `&self` arguments: As we saw [in the previous post][global-allocator], the global heap allocator is defined by adding the `#[global_allocator]` attribute to a `static` that implements the `GlobalAlloc` trait. Static variables are immutable in Rust, so there is no way to call a method that takes `&mut self` on the static allocator. For this reason, all the methods of `GlobalAlloc` only take an immutable `&self` reference.