Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Arbitrary self types v2: book changes. #4174

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading