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