Skip to content

Latest commit

 

History

History
30 lines (20 loc) · 909 Bytes

deref-coercions.md

File metadata and controls

30 lines (20 loc) · 909 Bytes

% Deref coercions

There is a new edition of the book and this is an old link.

Implementing the Deref trait allows us to customize the behavior of the dereference operator *. By implementing Deref in such a way that a smart pointer can be treated like a regular reference, we can write code that operates on references and use that code with smart pointers too.

use std::ops::Deref;

# struct MyBox<T>(T);
impl<T> Deref for MyBox<T> {
    type Target = T;

    fn deref(&self) -> &T {
        &self.0
    }
}

Here are the relevant sections in the new and old books: