Skip to content

Commit

Permalink
Arbitrary self types v2: book changes.
Browse files Browse the repository at this point in the history
Preliminary book changes for Arbitrary Self Types v2.

The listing number is currently out of order and this will need fixing,
I suspect, but keeping things there unchanged for reviewability
meanwhile.
  • Loading branch information
adetaylor committed Dec 20, 2024
1 parent 93f9ea4 commit 29722ea
Show file tree
Hide file tree
Showing 4 changed files with 59 additions and 0 deletions.
7 changes: 7 additions & 0 deletions listings/ch15-smart-pointers/listing-15-30/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions listings/ch15-smart-pointers/listing-15-30/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[package]
name = "deref-method-example"
version = "0.1.0"
edition = "2021"

[dependencies]
27 changes: 27 additions & 0 deletions listings/ch15-smart-pointers/listing-15-30/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
#![feature(arbitrary_self_types)]
// TODO remove before we land this

use std::ops::Deref;

struct CustomSmartPointer<T>(T);

impl<T> Deref for CustomSmartPointer<T> {
type Target = T;

fn deref(&self) -> &Self::Target {
&self.0
}
}

struct Pointee;

impl Pointee {
fn hello(self: &CustomSmartPointer<Self>) {
println!("Hello!");
}
}

fn main() {
let ptr = CustomSmartPointer(Pointee);
ptr.hello();
}
19 changes: 19 additions & 0 deletions src/ch15-02-deref.md
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,25 @@ match the parameter’s type. The number of times that `Deref::deref` needs to b
inserted is resolved at compile time, so there is no runtime penalty for taking
advantage of deref coercion!

### Calling methods on smart pointers

If your smart pointer implements `Deref` (or if it implements another trait,
called `Receiver`) then methods on the referent can also receive their `self`
type using your smart pointer.

<Listing number="15-30" file-name="src/main.rs" caption="Calling `hello` on a reference to a `MyBox<Foo>` value, which also works because of deref coercion">

```rust
{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-30/src/main.rs:here}}
```

</Listing>

You should normally implement `Deref` rather than directly implementing
`Receiver`. You'd implement `Receiver` only in cases where it's not safe to
create a reference to your smart pointer's referent, often in cases involving
cross-language interoperability.

### How Deref Coercion Interacts with Mutability

Similar to how you use the `Deref` trait to override the `*` operator on
Expand Down

0 comments on commit 29722ea

Please sign in to comment.