1/// Used for immutable dereferencing operations, like `*v`.
2///
3/// In addition to being used for explicit dereferencing operations with the
4/// (unary) `*` operator in immutable contexts, `Deref` is also used implicitly
5/// by the compiler in many circumstances. This mechanism is called
6/// ["`Deref` coercion"][coercion]. In mutable contexts, [`DerefMut`] is used and
7/// mutable deref coercion similarly occurs.
8///
9/// **Warning:** Deref coercion is a powerful language feature which has
10/// far-reaching implications for every type that implements `Deref`. The
11/// compiler will silently insert calls to `Deref::deref`. For this reason, one
12/// should be careful about implementing `Deref` and only do so when deref
13/// coercion is desirable. See [below][implementing] for advice on when this is
14/// typically desirable or undesirable.
15///
16/// Types that implement `Deref` or `DerefMut` are often called "smart
17/// pointers" and the mechanism of deref coercion has been specifically designed
18/// to facilitate the pointer-like behaviour that name suggests. Often, the
19/// purpose of a "smart pointer" type is to change the ownership semantics
20/// of a contained value (for example, [`Rc`][rc] or [`Cow`][cow]) or the
21/// storage semantics of a contained value (for example, [`Box`][box]).
22///
23/// # Deref coercion
24///
25/// If `T` implements `Deref<Target = U>`, and `v` is a value of type `T`, then:
26///
27/// * In immutable contexts, `*v` (where `T` is neither a reference nor a raw
28/// pointer) is equivalent to `*Deref::deref(&v)`.
29/// * Values of type `&T` are coerced to values of type `&U`
30/// * `T` implicitly implements all the methods of the type `U` which take the
31/// `&self` receiver.
32///
33/// For more details, visit [the chapter in *The Rust Programming Language*][book]
34/// as well as the reference sections on [the dereference operator][ref-deref-op],
35/// [method resolution], and [type coercions].
36///
37/// # When to implement `Deref` or `DerefMut`
38///
39/// The same advice applies to both deref traits. In general, deref traits
40/// **should** be implemented if:
41///
42/// 1. a value of the type transparently behaves like a value of the target
43/// type;
44/// 1. the implementation of the deref function is cheap; and
45/// 1. users of the type will not be surprised by any deref coercion behaviour.
46///
47/// In general, deref traits **should not** be implemented if:
48///
49/// 1. the deref implementations could fail unexpectedly; or
50/// 1. the type has methods that are likely to collide with methods on the
51/// target type; or
52/// 1. committing to deref coercion as part of the public API is not desirable.
53///
54/// Note that there's a large difference between implementing deref traits
55/// generically over many target types, and doing so only for specific target
56/// types.
57///
58/// Generic implementations, such as for [`Box<T>`][box] (which is generic over
59/// every type and dereferences to `T`) should be careful to provide few or no
60/// methods, since the target type is unknown and therefore every method could
61/// collide with one on the target type, causing confusion for users.
62/// `impl<T> Box<T>` has no methods (though several associated functions),
63/// partly for this reason.
64///
65/// Specific implementations, such as for [`String`][string] (whose `Deref`
66/// implementation has `Target = str`) can have many methods, since avoiding
67/// collision is much easier. `String` and `str` both have many methods, and
68/// `String` additionally behaves as if it has every method of `str` because of
69/// deref coercion. The implementing type may also be generic while the
70/// implementation is still specific in this sense; for example, [`Vec<T>`][vec]
71/// dereferences to `[T]`, so methods of `T` are not applicable.
72///
73/// Consider also that deref coercion means that deref traits are a much larger
74/// part of a type's public API than any other trait as it is implicitly called
75/// by the compiler. Therefore, it is advisable to consider whether this is
76/// something you are comfortable supporting as a public API.
77///
78/// The [`AsRef`] and [`Borrow`][core::borrow::Borrow] traits have very similar
79/// signatures to `Deref`. It may be desirable to implement either or both of
80/// these, whether in addition to or rather than deref traits. See their
81/// documentation for details.
82///
83/// # Fallibility
84///
85/// **This trait's method should never unexpectedly fail**. Deref coercion means
86/// the compiler will often insert calls to `Deref::deref` implicitly. Failure
87/// during dereferencing can be extremely confusing when `Deref` is invoked
88/// implicitly. In the majority of uses it should be infallible, though it may
89/// be acceptable to panic if the type is misused through programmer error, for
90/// example.
91///
92/// However, infallibility is not enforced and therefore not guaranteed.
93/// As such, `unsafe` code should not rely on infallibility in general for
94/// soundness.
95///
96/// [book]: ../../book/ch15-02-deref.html
97/// [coercion]: #deref-coercion
98/// [implementing]: #when-to-implement-deref-or-derefmut
99/// [ref-deref-op]: ../../reference/expressions/operator-expr.html#the-dereference-operator
100/// [method resolution]: ../../reference/expressions/method-call-expr.html
101/// [type coercions]: ../../reference/type-coercions.html
102/// [box]: ../../alloc/boxed/struct.Box.html
103/// [string]: ../../alloc/string/struct.String.html
104/// [vec]: ../../alloc/vec/struct.Vec.html
105/// [rc]: ../../alloc/rc/struct.Rc.html
106/// [cow]: ../../alloc/borrow/enum.Cow.html
107///
108/// # Examples
109///
110/// A struct with a single field which is accessible by dereferencing the
111/// struct.
112///
113/// ```
114/// use std::ops::Deref;
115///
116/// struct DerefExample<T> {
117/// value: T
118/// }
119///
120/// impl<T> Deref for DerefExample<T> {
121/// type Target = T;
122///
123/// fn deref(&self) -> &Self::Target {
124/// &self.value
125/// }
126/// }
127///
128/// let x = DerefExample { value: 'a' };
129/// assert_eq!('a', *x);
130/// ```
131#[lang = "deref"]
132#[doc(alias = "*")]
133#[doc(alias = "&*")]
134#[stable(feature = "rust1", since = "1.0.0")]
135#[rustc_diagnostic_item = "Deref"]
136pub trait Deref {
137 /// The resulting type after dereferencing.
138 #[stable(feature = "rust1", since = "1.0.0")]
139 #[rustc_diagnostic_item = "deref_target"]
140 #[lang = "deref_target"]
141 type Target: ?Sized;
142
143 /// Dereferences the value.
144 #[must_use]
145 #[stable(feature = "rust1", since = "1.0.0")]
146 #[rustc_diagnostic_item = "deref_method"]
147 fn deref(&self) -> &Self::Target;
148}
149
150#[stable(feature = "rust1", since = "1.0.0")]
151impl<T: ?Sized> Deref for &T {
152 type Target = T;
153
154 #[rustc_diagnostic_item = "noop_method_deref"]
155 fn deref(&self) -> &T {
156 *self
157 }
158}
159
160#[stable(feature = "rust1", since = "1.0.0")]
161impl<T: ?Sized> !DerefMut for &T {}
162
163#[stable(feature = "rust1", since = "1.0.0")]
164impl<T: ?Sized> Deref for &mut T {
165 type Target = T;
166
167 fn deref(&self) -> &T {
168 *self
169 }
170}
171
172/// Used for mutable dereferencing operations, like in `*v = 1;`.
173///
174/// In addition to being used for explicit dereferencing operations with the
175/// (unary) `*` operator in mutable contexts, `DerefMut` is also used implicitly
176/// by the compiler in many circumstances. This mechanism is called
177/// ["mutable deref coercion"][coercion]. In immutable contexts, [`Deref`] is used.
178///
179/// **Warning:** Deref coercion is a powerful language feature which has
180/// far-reaching implications for every type that implements `DerefMut`. The
181/// compiler will silently insert calls to `DerefMut::deref_mut`. For this
182/// reason, one should be careful about implementing `DerefMut` and only do so
183/// when mutable deref coercion is desirable. See [the `Deref` docs][implementing]
184/// for advice on when this is typically desirable or undesirable.
185///
186/// Types that implement `DerefMut` or `Deref` are often called "smart
187/// pointers" and the mechanism of deref coercion has been specifically designed
188/// to facilitate the pointer-like behaviour that name suggests. Often, the
189/// purpose of a "smart pointer" type is to change the ownership semantics
190/// of a contained value (for example, [`Rc`][rc] or [`Cow`][cow]) or the
191/// storage semantics of a contained value (for example, [`Box`][box]).
192///
193/// # Mutable deref coercion
194///
195/// If `T` implements `DerefMut<Target = U>`, and `v` is a value of type `T`,
196/// then:
197///
198/// * In mutable contexts, `*v` (where `T` is neither a reference nor a raw pointer)
199/// is equivalent to `*DerefMut::deref_mut(&mut v)`.
200/// * Values of type `&mut T` are coerced to values of type `&mut U`
201/// * `T` implicitly implements all the (mutable) methods of the type `U`.
202///
203/// For more details, visit [the chapter in *The Rust Programming Language*][book]
204/// as well as the reference sections on [the dereference operator][ref-deref-op],
205/// [method resolution] and [type coercions].
206///
207/// # Fallibility
208///
209/// **This trait's method should never unexpectedly fail**. Deref coercion means
210/// the compiler will often insert calls to `DerefMut::deref_mut` implicitly.
211/// Failure during dereferencing can be extremely confusing when `DerefMut` is
212/// invoked implicitly. In the majority of uses it should be infallible, though
213/// it may be acceptable to panic if the type is misused through programmer
214/// error, for example.
215///
216/// However, infallibility is not enforced and therefore not guaranteed.
217/// As such, `unsafe` code should not rely on infallibility in general for
218/// soundness.
219///
220/// [book]: ../../book/ch15-02-deref.html
221/// [coercion]: #mutable-deref-coercion
222/// [implementing]: Deref#when-to-implement-deref-or-derefmut
223/// [ref-deref-op]: ../../reference/expressions/operator-expr.html#the-dereference-operator
224/// [method resolution]: ../../reference/expressions/method-call-expr.html
225/// [type coercions]: ../../reference/type-coercions.html
226/// [box]: ../../alloc/boxed/struct.Box.html
227/// [string]: ../../alloc/string/struct.String.html
228/// [rc]: ../../alloc/rc/struct.Rc.html
229/// [cow]: ../../alloc/borrow/enum.Cow.html
230///
231/// # Examples
232///
233/// A struct with a single field which is modifiable by dereferencing the
234/// struct.
235///
236/// ```
237/// use std::ops::{Deref, DerefMut};
238///
239/// struct DerefMutExample<T> {
240/// value: T
241/// }
242///
243/// impl<T> Deref for DerefMutExample<T> {
244/// type Target = T;
245///
246/// fn deref(&self) -> &Self::Target {
247/// &self.value
248/// }
249/// }
250///
251/// impl<T> DerefMut for DerefMutExample<T> {
252/// fn deref_mut(&mut self) -> &mut Self::Target {
253/// &mut self.value
254/// }
255/// }
256///
257/// let mut x = DerefMutExample { value: 'a' };
258/// *x = 'b';
259/// assert_eq!('b', x.value);
260/// ```
261#[lang = "deref_mut"]
262#[doc(alias = "*")]
263#[stable(feature = "rust1", since = "1.0.0")]
264pub trait DerefMut: Deref {
265 /// Mutably dereferences the value.
266 #[stable(feature = "rust1", since = "1.0.0")]
267 #[rustc_diagnostic_item = "deref_mut_method"]
268 fn deref_mut(&mut self) -> &mut Self::Target;
269}
270
271#[stable(feature = "rust1", since = "1.0.0")]
272impl<T: ?Sized> DerefMut for &mut T {
273 fn deref_mut(&mut self) -> &mut T {
274 *self
275 }
276}
277
278/// Indicates that a struct can be used as a method receiver, without the
279/// `arbitrary_self_types` feature. This is implemented by stdlib pointer types like `Box<T>`,
280/// `Rc<T>`, `&T`, and `Pin<P>`.
281#[lang = "receiver"]
282#[unstable(feature = "receiver_trait", issue = "none")]
283#[doc(hidden)]
284pub trait Receiver {
285 // Empty.
286}
287
288#[unstable(feature = "receiver_trait", issue = "none")]
289impl<T: ?Sized> Receiver for &T {}
290
291#[unstable(feature = "receiver_trait", issue = "none")]
292impl<T: ?Sized> Receiver for &mut T {}
293