pub trait Deref {
type Target: ?Sized;
// Required method
fn deref(&self) -> &Self::Target;
}Expand description
Used for immutable dereferencing operations, like *v.
In addition to being used for explicit dereferencing operations with the
(unary) * operator in immutable contexts, Deref is also used implicitly
by the compiler in many circumstances. This mechanism is called
“Deref coercion”. In mutable contexts, DerefMut is used and
mutable deref coercion similarly occurs.
Warning: Deref coercion is a powerful language feature which has
far-reaching implications for every type that implements Deref. The
compiler will silently insert calls to Deref::deref. For this reason, one
should be careful about implementing Deref and only do so when deref
coercion is desirable. See below for advice on when this is
typically desirable or undesirable.
Types that implement Deref or DerefMut are often called “smart
pointers” and the mechanism of deref coercion has been specifically designed
to facilitate the pointer-like behavior that name suggests. Often, the
purpose of a “smart pointer” type is to change the ownership semantics
of a contained value (for example, Rc or Cow) or the
storage semantics of a contained value (for example, Box).
§Deref coercion
If T implements Deref<Target = U>, and v is a value of type T, then:
- In immutable contexts,
*v(whereTis neither a reference nor a raw pointer) is equivalent to*Deref::deref(&v). - Values of type
&Tare coerced to values of type&U Timplicitly implements all the methods of the typeUwhich take the&selfreceiver.
For more details, visit the chapter in The Rust Programming Language as well as the reference sections on the dereference operator, method resolution, and type coercions.
§When to implement Deref or DerefMut
The same advice applies to both deref traits. In general, deref traits should be implemented if:
- a value of the type transparently behaves like a value of the target type;
- the implementation of the deref function is cheap; and
- users of the type will not be surprised by any deref coercion behavior.
In general, deref traits should not be implemented if:
- the deref implementations could fail unexpectedly; or
- the type has methods that are likely to collide with methods on the target type; or
- committing to deref coercion as part of the public API is not desirable.
Note that there’s a large difference between implementing deref traits generically over many target types, and doing so only for specific target types.
Generic implementations, such as for Box<T> (which is generic over
every type and dereferences to T) should be careful to provide few or no
methods, since the target type is unknown and therefore every method could
collide with one on the target type, causing confusion for users.
impl<T> Box<T> has no methods (though several associated functions),
partly for this reason.
Specific implementations, such as for String (whose Deref
implementation has Target = str) can have many methods, since avoiding
collision is much easier. String and str both have many methods, and
String additionally behaves as if it has every method of str because of
deref coercion. The implementing type may also be generic while the
implementation is still specific in this sense; for example, Vec<T>
dereferences to [T], so methods of T are not applicable.
Consider also that deref coercion means that deref traits are a much larger part of a type’s public API than any other trait as it is implicitly called by the compiler. Therefore, it is advisable to consider whether this is something you are comfortable supporting as a public API.
The AsRef and Borrow traits have very similar
signatures to Deref. It may be desirable to implement either or both of
these, whether in addition to or rather than deref traits. See their
documentation for details.
§Fallibility
This trait’s method should never unexpectedly fail. Deref coercion means
the compiler will often insert calls to Deref::deref implicitly. Failure
during dereferencing can be extremely confusing when Deref is invoked
implicitly. In the majority of uses it should be infallible, though it may
be acceptable to panic if the type is misused through programmer error, for
example.
However, infallibility is not enforced and therefore not guaranteed.
As such, unsafe code should not rely on infallibility in general for
soundness.
§Examples
A struct with a single field which is accessible by dereferencing the struct.
use std::ops::Deref;
struct DerefExample<T> {
value: T
}
impl<T> Deref for DerefExample<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.value
}
}
let x = DerefExample { value: 'a' };
assert_eq!('a', *x);Required Associated Types§
Required Methods§
Dyn Compatibility§
This trait is dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".
Implementors§
Source§impl Deref for AbortSignal
impl Deref for AbortSignal
type Target = EventTarget
Source§impl Deref for DateTimeRangeFormatPart
impl Deref for DateTimeRangeFormatPart
type Target = DateTimeFormatPart
Source§impl Deref for DedicatedWorkerGlobalScope
impl Deref for DedicatedWorkerGlobalScope
type Target = WorkerGlobalScope
Source§impl Deref for EventSource
impl Deref for EventSource
type Target = EventTarget
Source§impl Deref for FileReader
impl Deref for FileReader
type Target = EventTarget
Source§impl Deref for HtmlHeadElement
impl Deref for HtmlHeadElement
type Target = HtmlElement
Source§impl Deref for HtmlInputElement
impl Deref for HtmlInputElement
type Target = HtmlElement
Source§impl Deref for NumberRangeFormatPart
impl Deref for NumberRangeFormatPart
type Target = NumberFormatPart
Source§impl Deref for ResolvedCollatorOptions
impl Deref for ResolvedCollatorOptions
type Target = CollatorOptions
Source§impl Deref for ResolvedDisplayNamesOptions
impl Deref for ResolvedDisplayNamesOptions
type Target = DisplayNamesOptions
Source§impl Deref for ResolvedListFormatOptions
impl Deref for ResolvedListFormatOptions
type Target = ListFormatOptions
Source§impl Deref for ResolvedNumberFormatOptions
impl Deref for ResolvedNumberFormatOptions
type Target = NumberFormatOptions
Source§impl Deref for ResolvedPluralRulesOptions
impl Deref for ResolvedPluralRulesOptions
type Target = PluralRulesOptions
Source§impl Deref for ResolvedSegmenterOptions
impl Deref for ResolvedSegmenterOptions
type Target = SegmenterOptions
Source§impl Deref for TranspositionTable
impl Deref for TranspositionTable
Source§impl Deref for WorkerGlobalScope
impl Deref for WorkerGlobalScope
type Target = EventTarget
Source§impl<'py, T> Deref for Bound<'py, T>where
T: DerefToPyAny,
impl<'py, T> Deref for Bound<'py, T>where
T: DerefToPyAny,
Source§impl<Ptr, BR> Deref for FilePtr<Ptr, BR>where
Ptr: IntoSeekFrom,
BR: BinRead,
§Panics
Will panic if the FilePtr has not been read yet using BinRead::after_parse
impl<Ptr, BR> Deref for FilePtr<Ptr, BR>where
Ptr: IntoSeekFrom,
BR: BinRead,
§Panics
Will panic if the FilePtr has not been read yet using BinRead::after_parse
Source§impl<T, P> Deref for Punctuated<T, P>
impl<T, P> Deref for Punctuated<T, P>
Source§impl<T> Deref for JsStatic<T>where
T: FromWasmAbi + 'static,
Available on crate feature std and non-target feature atomics only.
impl<T> Deref for JsStatic<T>where
T: FromWasmAbi + 'static,
std and non-target feature atomics only.