core/ops/deref.rs
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 behavior 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 behavior.
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"]
136#[const_trait]
137#[rustc_const_unstable(feature = "const_deref", issue = "88955")]
138pub trait Deref {
139 /// The resulting type after dereferencing.
140 #[stable(feature = "rust1", since = "1.0.0")]
141 #[rustc_diagnostic_item = "deref_target"]
142 #[lang = "deref_target"]
143 type Target: ?Sized;
144
145 /// Dereferences the value.
146 #[must_use]
147 #[stable(feature = "rust1", since = "1.0.0")]
148 #[rustc_diagnostic_item = "deref_method"]
149 fn deref(&self) -> &Self::Target;
150}
151
152#[stable(feature = "rust1", since = "1.0.0")]
153impl<T: ?Sized> const Deref for &T {
154 type Target = T;
155
156 #[rustc_diagnostic_item = "noop_method_deref"]
157 fn deref(&self) -> &T {
158 *self
159 }
160}
161
162#[stable(feature = "rust1", since = "1.0.0")]
163impl<T: ?Sized> !DerefMut for &T {}
164
165#[stable(feature = "rust1", since = "1.0.0")]
166impl<T: ?Sized> const Deref for &mut T {
167 type Target = T;
168
169 fn deref(&self) -> &T {
170 *self
171 }
172}
173
174/// Used for mutable dereferencing operations, like in `*v = 1;`.
175///
176/// In addition to being used for explicit dereferencing operations with the
177/// (unary) `*` operator in mutable contexts, `DerefMut` is also used implicitly
178/// by the compiler in many circumstances. This mechanism is called
179/// ["mutable deref coercion"][coercion]. In immutable contexts, [`Deref`] is used.
180///
181/// **Warning:** Deref coercion is a powerful language feature which has
182/// far-reaching implications for every type that implements `DerefMut`. The
183/// compiler will silently insert calls to `DerefMut::deref_mut`. For this
184/// reason, one should be careful about implementing `DerefMut` and only do so
185/// when mutable deref coercion is desirable. See [the `Deref` docs][implementing]
186/// for advice on when this is typically desirable or undesirable.
187///
188/// Types that implement `DerefMut` or `Deref` are often called "smart
189/// pointers" and the mechanism of deref coercion has been specifically designed
190/// to facilitate the pointer-like behavior that name suggests. Often, the
191/// purpose of a "smart pointer" type is to change the ownership semantics
192/// of a contained value (for example, [`Rc`][rc] or [`Cow`][cow]) or the
193/// storage semantics of a contained value (for example, [`Box`][box]).
194///
195/// # Mutable deref coercion
196///
197/// If `T` implements `DerefMut<Target = U>`, and `v` is a value of type `T`,
198/// then:
199///
200/// * In mutable contexts, `*v` (where `T` is neither a reference nor a raw pointer)
201/// is equivalent to `*DerefMut::deref_mut(&mut v)`.
202/// * Values of type `&mut T` are coerced to values of type `&mut U`
203/// * `T` implicitly implements all the (mutable) methods of the type `U`.
204///
205/// For more details, visit [the chapter in *The Rust Programming Language*][book]
206/// as well as the reference sections on [the dereference operator][ref-deref-op],
207/// [method resolution] and [type coercions].
208///
209/// # Fallibility
210///
211/// **This trait's method should never unexpectedly fail**. Deref coercion means
212/// the compiler will often insert calls to `DerefMut::deref_mut` implicitly.
213/// Failure during dereferencing can be extremely confusing when `DerefMut` is
214/// invoked implicitly. In the majority of uses it should be infallible, though
215/// it may be acceptable to panic if the type is misused through programmer
216/// error, for example.
217///
218/// However, infallibility is not enforced and therefore not guaranteed.
219/// As such, `unsafe` code should not rely on infallibility in general for
220/// soundness.
221///
222/// [book]: ../../book/ch15-02-deref.html
223/// [coercion]: #mutable-deref-coercion
224/// [implementing]: Deref#when-to-implement-deref-or-derefmut
225/// [ref-deref-op]: ../../reference/expressions/operator-expr.html#the-dereference-operator
226/// [method resolution]: ../../reference/expressions/method-call-expr.html
227/// [type coercions]: ../../reference/type-coercions.html
228/// [box]: ../../alloc/boxed/struct.Box.html
229/// [string]: ../../alloc/string/struct.String.html
230/// [rc]: ../../alloc/rc/struct.Rc.html
231/// [cow]: ../../alloc/borrow/enum.Cow.html
232///
233/// # Examples
234///
235/// A struct with a single field which is modifiable by dereferencing the
236/// struct.
237///
238/// ```
239/// use std::ops::{Deref, DerefMut};
240///
241/// struct DerefMutExample<T> {
242/// value: T
243/// }
244///
245/// impl<T> Deref for DerefMutExample<T> {
246/// type Target = T;
247///
248/// fn deref(&self) -> &Self::Target {
249/// &self.value
250/// }
251/// }
252///
253/// impl<T> DerefMut for DerefMutExample<T> {
254/// fn deref_mut(&mut self) -> &mut Self::Target {
255/// &mut self.value
256/// }
257/// }
258///
259/// let mut x = DerefMutExample { value: 'a' };
260/// *x = 'b';
261/// assert_eq!('b', x.value);
262/// ```
263#[lang = "deref_mut"]
264#[doc(alias = "*")]
265#[stable(feature = "rust1", since = "1.0.0")]
266#[const_trait]
267#[rustc_const_unstable(feature = "const_deref", issue = "88955")]
268pub trait DerefMut: ~const Deref {
269 /// Mutably dereferences the value.
270 #[stable(feature = "rust1", since = "1.0.0")]
271 #[rustc_diagnostic_item = "deref_mut_method"]
272 fn deref_mut(&mut self) -> &mut Self::Target;
273}
274
275#[stable(feature = "rust1", since = "1.0.0")]
276impl<T: ?Sized> const DerefMut for &mut T {
277 fn deref_mut(&mut self) -> &mut T {
278 *self
279 }
280}
281
282/// Perma-unstable marker trait. Indicates that the type has a well-behaved [`Deref`]
283/// (and, if applicable, [`DerefMut`]) implementation. This is relied on for soundness
284/// of deref patterns.
285///
286/// FIXME(deref_patterns): The precise semantics are undecided; the rough idea is that
287/// successive calls to `deref`/`deref_mut` without intermediate mutation should be
288/// idempotent, in the sense that they return the same value as far as pattern-matching
289/// is concerned. Calls to `deref`/`deref_mut` must leave the pointer itself likewise
290/// unchanged.
291#[unstable(feature = "deref_pure_trait", issue = "87121")]
292#[lang = "deref_pure"]
293pub unsafe trait DerefPure {}
294
295#[unstable(feature = "deref_pure_trait", issue = "87121")]
296unsafe impl<T: ?Sized> DerefPure for &T {}
297
298#[unstable(feature = "deref_pure_trait", issue = "87121")]
299unsafe impl<T: ?Sized> DerefPure for &mut T {}
300
301/// Indicates that a struct can be used as a method receiver.
302/// That is, a type can use this type as a type of `self`, like this:
303/// ```compile_fail
304/// # // This is currently compile_fail because the compiler-side parts
305/// # // of arbitrary_self_types are not implemented
306/// use std::ops::Receiver;
307///
308/// struct SmartPointer<T>(T);
309///
310/// impl<T> Receiver for SmartPointer<T> {
311/// type Target = T;
312/// }
313///
314/// struct MyContainedType;
315///
316/// impl MyContainedType {
317/// fn method(self: SmartPointer<Self>) {
318/// // ...
319/// }
320/// }
321///
322/// fn main() {
323/// let ptr = SmartPointer(MyContainedType);
324/// ptr.method();
325/// }
326/// ```
327/// This trait is blanket implemented for any type which implements
328/// [`Deref`], which includes stdlib pointer types like `Box<T>`,`Rc<T>`, `&T`,
329/// and `Pin<P>`. For that reason, it's relatively rare to need to
330/// implement this directly. You'll typically do this only if you need
331/// to implement a smart pointer type which can't implement [`Deref`]; perhaps
332/// because you're interfacing with another programming language and can't
333/// guarantee that references comply with Rust's aliasing rules.
334///
335/// When looking for method candidates, Rust will explore a chain of possible
336/// `Receiver`s, so for example each of the following methods work:
337/// ```
338/// use std::boxed::Box;
339/// use std::rc::Rc;
340///
341/// // Both `Box` and `Rc` (indirectly) implement Receiver
342///
343/// struct MyContainedType;
344///
345/// fn main() {
346/// let t = Rc::new(Box::new(MyContainedType));
347/// t.method_a();
348/// t.method_b();
349/// t.method_c();
350/// }
351///
352/// impl MyContainedType {
353/// fn method_a(&self) {
354///
355/// }
356/// fn method_b(self: &Box<Self>) {
357///
358/// }
359/// fn method_c(self: &Rc<Box<Self>>) {
360///
361/// }
362/// }
363/// ```
364#[lang = "receiver"]
365#[unstable(feature = "arbitrary_self_types", issue = "44874")]
366pub trait Receiver {
367 /// The target type on which the method may be called.
368 #[rustc_diagnostic_item = "receiver_target"]
369 #[lang = "receiver_target"]
370 #[unstable(feature = "arbitrary_self_types", issue = "44874")]
371 type Target: ?Sized;
372}
373
374#[unstable(feature = "arbitrary_self_types", issue = "44874")]
375impl<P: ?Sized, T: ?Sized> Receiver for P
376where
377 P: Deref<Target = T>,
378{
379 type Target = T;
380}
381
382/// Indicates that a struct can be used as a method receiver, without the
383/// `arbitrary_self_types` feature. This is implemented by stdlib pointer types like `Box<T>`,
384/// `Rc<T>`, `&T`, and `Pin<P>`.
385///
386/// This trait will shortly be removed and replaced with a more generic
387/// facility based around the current "arbitrary self types" unstable feature.
388/// That new facility will use the replacement trait above called `Receiver`
389/// which is why this is now named `LegacyReceiver`.
390#[lang = "legacy_receiver"]
391#[unstable(feature = "legacy_receiver_trait", issue = "none")]
392#[doc(hidden)]
393pub trait LegacyReceiver {
394 // Empty.
395}
396
397#[unstable(feature = "legacy_receiver_trait", issue = "none")]
398impl<T: ?Sized> LegacyReceiver for &T {}
399
400#[unstable(feature = "legacy_receiver_trait", issue = "none")]
401impl<T: ?Sized> LegacyReceiver for &mut T {}