core/ops/deref.rs
1use crate::marker::PointeeSized;
2
3/// Used for immutable dereferencing operations, like `*v`.
4///
5/// In addition to being used for explicit dereferencing operations with the
6/// (unary) `*` operator in immutable contexts, `Deref` is also used implicitly
7/// by the compiler in many circumstances. This mechanism is called
8/// ["`Deref` coercion"][coercion]. In mutable contexts, [`DerefMut`] is used and
9/// mutable deref coercion similarly occurs.
10///
11/// **Warning:** Deref coercion is a powerful language feature which has
12/// far-reaching implications for every type that implements `Deref`. The
13/// compiler will silently insert calls to `Deref::deref`. For this reason, one
14/// should be careful about implementing `Deref` and only do so when deref
15/// coercion is desirable. See [below][implementing] for advice on when this is
16/// typically desirable or undesirable.
17///
18/// Types that implement `Deref` or `DerefMut` are often called "smart
19/// pointers" and the mechanism of deref coercion has been specifically designed
20/// to facilitate the pointer-like behavior that name suggests. Often, the
21/// purpose of a "smart pointer" type is to change the ownership semantics
22/// of a contained value (for example, [`Rc`][rc] or [`Cow`][cow]) or the
23/// storage semantics of a contained value (for example, [`Box`][box]).
24///
25/// # Deref coercion
26///
27/// If `T` implements `Deref<Target = U>`, and `v` is a value of type `T`, then:
28///
29/// * In immutable contexts, `*v` (where `T` is neither a reference nor a raw
30/// pointer) is equivalent to `*Deref::deref(&v)`.
31/// * Values of type `&T` are coerced to values of type `&U`
32/// * `T` implicitly implements all the methods of the type `U` which take the
33/// `&self` receiver.
34///
35/// For more details, visit [the chapter in *The Rust Programming Language*][book]
36/// as well as the reference sections on [the dereference operator][ref-deref-op],
37/// [method resolution], and [type coercions].
38///
39/// # When to implement `Deref` or `DerefMut`
40///
41/// The same advice applies to both deref traits. In general, deref traits
42/// **should** be implemented if:
43///
44/// 1. a value of the type transparently behaves like a value of the target
45/// type;
46/// 1. the implementation of the deref function is cheap; and
47/// 1. users of the type will not be surprised by any deref coercion behavior.
48///
49/// In general, deref traits **should not** be implemented if:
50///
51/// 1. the deref implementations could fail unexpectedly; or
52/// 1. the type has methods that are likely to collide with methods on the
53/// target type; or
54/// 1. committing to deref coercion as part of the public API is not desirable.
55///
56/// Note that there's a large difference between implementing deref traits
57/// generically over many target types, and doing so only for specific target
58/// types.
59///
60/// Generic implementations, such as for [`Box<T>`][box] (which is generic over
61/// every type and dereferences to `T`) should be careful to provide few or no
62/// methods, since the target type is unknown and therefore every method could
63/// collide with one on the target type, causing confusion for users.
64/// `impl<T> Box<T>` has no methods (though several associated functions),
65/// partly for this reason.
66///
67/// Specific implementations, such as for [`String`][string] (whose `Deref`
68/// implementation has `Target = str`) can have many methods, since avoiding
69/// collision is much easier. `String` and `str` both have many methods, and
70/// `String` additionally behaves as if it has every method of `str` because of
71/// deref coercion. The implementing type may also be generic while the
72/// implementation is still specific in this sense; for example, [`Vec<T>`][vec]
73/// dereferences to `[T]`, so methods of `T` are not applicable.
74///
75/// Consider also that deref coercion means that deref traits are a much larger
76/// part of a type's public API than any other trait as it is implicitly called
77/// by the compiler. Therefore, it is advisable to consider whether this is
78/// something you are comfortable supporting as a public API.
79///
80/// The [`AsRef`] and [`Borrow`][core::borrow::Borrow] traits have very similar
81/// signatures to `Deref`. It may be desirable to implement either or both of
82/// these, whether in addition to or rather than deref traits. See their
83/// documentation for details.
84///
85/// # Fallibility
86///
87/// **This trait's method should never unexpectedly fail**. Deref coercion means
88/// the compiler will often insert calls to `Deref::deref` implicitly. Failure
89/// during dereferencing can be extremely confusing when `Deref` is invoked
90/// implicitly. In the majority of uses it should be infallible, though it may
91/// be acceptable to panic if the type is misused through programmer error, for
92/// example.
93///
94/// However, infallibility is not enforced and therefore not guaranteed.
95/// As such, `unsafe` code should not rely on infallibility in general for
96/// soundness.
97///
98/// [book]: ../../book/ch15-02-deref.html
99/// [coercion]: #deref-coercion
100/// [implementing]: #when-to-implement-deref-or-derefmut
101/// [ref-deref-op]: ../../reference/expressions/operator-expr.html#the-dereference-operator
102/// [method resolution]: ../../reference/expressions/method-call-expr.html
103/// [type coercions]: ../../reference/type-coercions.html
104/// [box]: ../../alloc/boxed/struct.Box.html
105/// [string]: ../../alloc/string/struct.String.html
106/// [vec]: ../../alloc/vec/struct.Vec.html
107/// [rc]: ../../alloc/rc/struct.Rc.html
108/// [cow]: ../../alloc/borrow/enum.Cow.html
109///
110/// # Examples
111///
112/// A struct with a single field which is accessible by dereferencing the
113/// struct.
114///
115/// ```
116/// use std::ops::Deref;
117///
118/// struct DerefExample<T> {
119/// value: T
120/// }
121///
122/// impl<T> Deref for DerefExample<T> {
123/// type Target = T;
124///
125/// fn deref(&self) -> &Self::Target {
126/// &self.value
127/// }
128/// }
129///
130/// let x = DerefExample { value: 'a' };
131/// assert_eq!('a', *x);
132/// ```
133#[lang = "deref"]
134#[doc(alias = "*")]
135#[doc(alias = "&*")]
136#[stable(feature = "rust1", since = "1.0.0")]
137#[rustc_diagnostic_item = "Deref"]
138#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
139pub const trait Deref: PointeeSized {
140 /// The resulting type after dereferencing.
141 #[stable(feature = "rust1", since = "1.0.0")]
142 #[rustc_diagnostic_item = "deref_target"]
143 #[lang = "deref_target"]
144 type Target: ?Sized;
145
146 /// Dereferences the value.
147 #[must_use]
148 #[stable(feature = "rust1", since = "1.0.0")]
149 #[rustc_diagnostic_item = "deref_method"]
150 fn deref(&self) -> &Self::Target;
151}
152
153#[stable(feature = "rust1", since = "1.0.0")]
154#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
155impl<T: ?Sized> const Deref for &T {
156 type Target = T;
157
158 #[rustc_diagnostic_item = "noop_method_deref"]
159 #[ferrocene::prevalidated]
160 fn deref(&self) -> &T {
161 self
162 }
163}
164
165#[stable(feature = "rust1", since = "1.0.0")]
166impl<T: ?Sized> !DerefMut for &T {}
167
168#[stable(feature = "rust1", since = "1.0.0")]
169#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
170impl<T: ?Sized> const Deref for &mut T {
171 type Target = T;
172
173 #[ferrocene::prevalidated]
174 fn deref(&self) -> &T {
175 self
176 }
177}
178
179/// Used for mutable dereferencing operations, like in `*v = 1;`.
180///
181/// In addition to being used for explicit dereferencing operations with the
182/// (unary) `*` operator in mutable contexts, `DerefMut` is also used implicitly
183/// by the compiler in many circumstances. This mechanism is called
184/// ["mutable deref coercion"][coercion]. In immutable contexts, [`Deref`] is used.
185///
186/// **Warning:** Deref coercion is a powerful language feature which has
187/// far-reaching implications for every type that implements `DerefMut`. The
188/// compiler will silently insert calls to `DerefMut::deref_mut`. For this
189/// reason, one should be careful about implementing `DerefMut` and only do so
190/// when mutable deref coercion is desirable. See [the `Deref` docs][implementing]
191/// for advice on when this is typically desirable or undesirable.
192///
193/// Types that implement `DerefMut` or `Deref` are often called "smart
194/// pointers" and the mechanism of deref coercion has been specifically designed
195/// to facilitate the pointer-like behavior that name suggests. Often, the
196/// purpose of a "smart pointer" type is to change the ownership semantics
197/// of a contained value (for example, [`Rc`][rc] or [`Cow`][cow]) or the
198/// storage semantics of a contained value (for example, [`Box`][box]).
199///
200/// # Mutable deref coercion
201///
202/// If `T` implements `DerefMut<Target = U>`, and `v` is a value of type `T`,
203/// then:
204///
205/// * In mutable contexts, `*v` (where `T` is neither a reference nor a raw pointer)
206/// is equivalent to `*DerefMut::deref_mut(&mut v)`.
207/// * Values of type `&mut T` are coerced to values of type `&mut U`
208/// * `T` implicitly implements all the (mutable) methods of the type `U`.
209///
210/// For more details, visit [the chapter in *The Rust Programming Language*][book]
211/// as well as the reference sections on [the dereference operator][ref-deref-op],
212/// [method resolution] and [type coercions].
213///
214/// # Fallibility
215///
216/// **This trait's method should never unexpectedly fail**. Deref coercion means
217/// the compiler will often insert calls to `DerefMut::deref_mut` implicitly.
218/// Failure during dereferencing can be extremely confusing when `DerefMut` is
219/// invoked implicitly. In the majority of uses it should be infallible, though
220/// it may be acceptable to panic if the type is misused through programmer
221/// error, for example.
222///
223/// However, infallibility is not enforced and therefore not guaranteed.
224/// As such, `unsafe` code should not rely on infallibility in general for
225/// soundness.
226///
227/// [book]: ../../book/ch15-02-deref.html
228/// [coercion]: #mutable-deref-coercion
229/// [implementing]: Deref#when-to-implement-deref-or-derefmut
230/// [ref-deref-op]: ../../reference/expressions/operator-expr.html#the-dereference-operator
231/// [method resolution]: ../../reference/expressions/method-call-expr.html
232/// [type coercions]: ../../reference/type-coercions.html
233/// [box]: ../../alloc/boxed/struct.Box.html
234/// [string]: ../../alloc/string/struct.String.html
235/// [rc]: ../../alloc/rc/struct.Rc.html
236/// [cow]: ../../alloc/borrow/enum.Cow.html
237///
238/// # Examples
239///
240/// A struct with a single field which is modifiable by dereferencing the
241/// struct.
242///
243/// ```
244/// use std::ops::{Deref, DerefMut};
245///
246/// struct DerefMutExample<T> {
247/// value: T
248/// }
249///
250/// impl<T> Deref for DerefMutExample<T> {
251/// type Target = T;
252///
253/// fn deref(&self) -> &Self::Target {
254/// &self.value
255/// }
256/// }
257///
258/// impl<T> DerefMut for DerefMutExample<T> {
259/// fn deref_mut(&mut self) -> &mut Self::Target {
260/// &mut self.value
261/// }
262/// }
263///
264/// let mut x = DerefMutExample { value: 'a' };
265/// *x = 'b';
266/// assert_eq!('b', x.value);
267/// ```
268#[lang = "deref_mut"]
269#[doc(alias = "*")]
270#[stable(feature = "rust1", since = "1.0.0")]
271#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
272pub const trait DerefMut: [const] Deref + PointeeSized {
273 /// Mutably dereferences the value.
274 #[stable(feature = "rust1", since = "1.0.0")]
275 #[rustc_diagnostic_item = "deref_mut_method"]
276 fn deref_mut(&mut self) -> &mut Self::Target;
277}
278
279#[stable(feature = "rust1", since = "1.0.0")]
280#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
281impl<T: ?Sized> const DerefMut for &mut T {
282 #[ferrocene::prevalidated]
283 fn deref_mut(&mut self) -> &mut T {
284 self
285 }
286}
287
288/// Perma-unstable marker trait. Indicates that the type has a well-behaved [`Deref`]
289/// (and, if applicable, [`DerefMut`]) implementation. This is relied on for soundness
290/// of deref patterns.
291///
292/// FIXME(deref_patterns): The precise semantics are undecided; the rough idea is that
293/// successive calls to `deref`/`deref_mut` without intermediate mutation should be
294/// idempotent, in the sense that they return the same value as far as pattern-matching
295/// is concerned. Calls to `deref`/`deref_mut` must leave the pointer itself likewise
296/// unchanged.
297#[unstable(feature = "deref_pure_trait", issue = "87121")]
298#[lang = "deref_pure"]
299#[rustc_dyn_incompatible_trait]
300pub unsafe trait DerefPure: PointeeSized {}
301
302#[unstable(feature = "deref_pure_trait", issue = "87121")]
303unsafe impl<T: ?Sized> DerefPure for &T {}
304
305#[unstable(feature = "deref_pure_trait", issue = "87121")]
306unsafe impl<T: ?Sized> DerefPure for &mut T {}
307
308/// Indicates that a struct can be used as a method receiver.
309/// That is, a type can use this type as a type of `self`, like this:
310/// ```compile_fail
311/// # // This is currently compile_fail because the compiler-side parts
312/// # // of arbitrary_self_types are not implemented
313/// use std::ops::Receiver;
314///
315/// struct SmartPointer<T>(T);
316///
317/// impl<T> Receiver for SmartPointer<T> {
318/// type Target = T;
319/// }
320///
321/// struct MyContainedType;
322///
323/// impl MyContainedType {
324/// fn method(self: SmartPointer<Self>) {
325/// // ...
326/// }
327/// }
328///
329/// fn main() {
330/// let ptr = SmartPointer(MyContainedType);
331/// ptr.method();
332/// }
333/// ```
334/// This trait is blanket implemented for any type which implements
335/// [`Deref`], which includes stdlib pointer types like `Box<T>`,`Rc<T>`, `&T`,
336/// and `Pin<P>`. For that reason, it's relatively rare to need to
337/// implement this directly. You'll typically do this only if you need
338/// to implement a smart pointer type which can't implement [`Deref`]; perhaps
339/// because you're interfacing with another programming language and can't
340/// guarantee that references comply with Rust's aliasing rules.
341///
342/// When looking for method candidates, Rust will explore a chain of possible
343/// `Receiver`s, so for example each of the following methods work:
344/// ```
345/// use std::boxed::Box;
346/// use std::rc::Rc;
347///
348/// // Both `Box` and `Rc` (indirectly) implement Receiver
349///
350/// struct MyContainedType;
351///
352/// fn main() {
353/// let t = Rc::new(Box::new(MyContainedType));
354/// t.method_a();
355/// t.method_b();
356/// t.method_c();
357/// }
358///
359/// impl MyContainedType {
360/// fn method_a(&self) {
361///
362/// }
363/// fn method_b(self: &Box<Self>) {
364///
365/// }
366/// fn method_c(self: &Rc<Box<Self>>) {
367///
368/// }
369/// }
370/// ```
371#[lang = "receiver"]
372#[unstable(feature = "arbitrary_self_types", issue = "44874")]
373pub trait Receiver: PointeeSized {
374 /// The target type on which the method may be called.
375 #[rustc_diagnostic_item = "receiver_target"]
376 #[lang = "receiver_target"]
377 #[unstable(feature = "arbitrary_self_types", issue = "44874")]
378 type Target: ?Sized;
379}
380
381#[unstable(feature = "arbitrary_self_types", issue = "44874")]
382impl<P: ?Sized, T: ?Sized> Receiver for P
383where
384 P: Deref<Target = T>,
385{
386 type Target = T;
387}
388
389/// Indicates that a struct can be used as a method receiver, without the
390/// `arbitrary_self_types` feature. This is implemented by stdlib pointer types like `Box<T>`,
391/// `Rc<T>`, `&T`, and `Pin<P>`.
392///
393/// This trait will shortly be removed and replaced with a more generic
394/// facility based around the current "arbitrary self types" unstable feature.
395/// That new facility will use the replacement trait above called `Receiver`
396/// which is why this is now named `LegacyReceiver`.
397#[lang = "legacy_receiver"]
398#[unstable(feature = "legacy_receiver_trait", issue = "none")]
399#[doc(hidden)]
400pub trait LegacyReceiver: PointeeSized {
401 // Empty.
402}
403
404#[unstable(feature = "legacy_receiver_trait", issue = "none")]
405impl<T: PointeeSized> LegacyReceiver for &T {}
406
407#[unstable(feature = "legacy_receiver_trait", issue = "none")]
408impl<T: PointeeSized> LegacyReceiver for &mut T {}