Skip to main content

Deref

Trait Deref 

1.0.0 (const: unstable) · Source
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 (where T is neither a reference nor a raw pointer) is equivalent to *Deref::deref(&v).
  • Values of type &T are coerced to values of type &U
  • T implicitly implements all the methods of the type U which take the &self receiver.

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:

  1. a value of the type transparently behaves like a value of the target type;
  2. the implementation of the deref function is cheap; and
  3. users of the type will not be surprised by any deref coercion behavior.

In general, deref traits should not be implemented if:

  1. the deref implementations could fail unexpectedly; or
  2. the type has methods that are likely to collide with methods on the target type; or
  3. 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§

1.0.0 (const: unstable) · Source

type Target: ?Sized

The resulting type after dereferencing.

Required Methods§

1.0.0 (const: unstable) · Source

fn deref(&self) -> &Self::Target

Dereferences the value.

Dyn Compatibility§

This trait is dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§

Source§

impl Deref for AbortSignal

Source§

impl Deref for AddEventListenerOptions

Source§

impl Deref for ArrayBuffer

Source§

impl Deref for ArrayBufferOptions

Source§

impl Deref for BigInt

Source§

impl Deref for BigInt64Array

Source§

impl Deref for BigUint64Array

Source§

impl Deref for Blob

Source§

impl Deref for BlobPropertyBag

Source§

impl Deref for Board

Source§

impl Deref for Boolean

Source§

impl Deref for ByteStr

Source§

impl Deref for ByteString

Source§

impl Deref for Bytes

Source§

impl Deref for BytesMut

1.0.0 · Source§

impl Deref for CString

Source§

impl Deref for CloseEvent

Source§

impl Deref for CloseEventInit

Source§

impl Deref for Collator

Source§

impl Deref for CollatorOptions

Source§

impl Deref for ColoredString

Source§

impl Deref for CompileError

Source§

impl Deref for DataView

Source§

impl Deref for Date

Source§

impl Deref for DateTimeFormat

Source§

impl Deref for DateTimeFormatOptions

Source§

impl Deref for DateTimeFormatPart

Source§

impl Deref for DateTimeRangeFormatPart

Source§

impl Deref for DedicatedWorkerGlobalScope

Source§

impl Deref for DisplayNames

Source§

impl Deref for DisplayNamesOptions

Source§

impl Deref for Document

Source§

impl Deref for DomException

Source§

impl Deref for Duration

Source§

impl Deref for DurationFormat

Source§

impl Deref for DurationFormatOptions

Source§

impl Deref for DurationFormatPart

Source§

impl Deref for Element

Source§

impl Deref for Error

Source§

impl Deref for ErrorEvent

Source§

impl Deref for EvalError

Source§

impl Deref for Evaluator

Source§

impl Deref for Event

Source§

impl Deref for EventSource

Source§

impl Deref for EventSourceInit

Source§

impl Deref for EventTarget

Source§

impl Deref for Exception

Source§

impl Deref for web_sys::features::gen_File::File

Source§

impl Deref for gloo_file::blob::File

Source§

impl Deref for web_sys::features::gen_FileList::FileList

Source§

impl Deref for gloo_file::file_list::FileList

Source§

impl Deref for FilePropertyBag

Source§

impl Deref for FileReader

Source§

impl Deref for Float16Array

Source§

impl Deref for Float32Array

Source§

impl Deref for Float64Array

Source§

impl Deref for FormData

Source§

impl Deref for Global

Source§

impl Deref for Headers

Source§

impl Deref for History

Source§

impl Deref for HtmlElement

Source§

impl Deref for HtmlHeadElement

Source§

impl Deref for HtmlInputElement

Source§

impl Deref for Instance

Source§

impl Deref for Int8Array

Source§

impl Deref for Int16Array

Source§

impl Deref for Int32Array

Source§

impl Deref for JsString

Source§

impl Deref for LinkError

Source§

impl Deref for ListFormat

Source§

impl Deref for ListFormatOptions

Source§

impl Deref for ListFormatPart

Source§

impl Deref for Locale

Source§

impl Deref for LocaleMatcherOptions

Source§

impl Deref for Location

Source§

impl Deref for Memory

Source§

impl Deref for MessageEvent

Source§

impl Deref for Module

Source§

impl Deref for Node

Source§

impl Deref for Null

Source§

impl Deref for NullString

Source§

impl Deref for NullWideString

Source§

impl Deref for Number

Source§

impl Deref for NumberFormat

Source§

impl Deref for NumberFormatOptions

Source§

impl Deref for NumberFormatPart

Source§

impl Deref for NumberRangeFormatPart

Source§

impl Deref for ObjectUrl

Source§

impl Deref for ObserverCallback

1.0.0 · Source§

impl Deref for OsString

1.0.0 · Source§

impl Deref for PathBuf

Source§

impl Deref for PluralRules

Source§

impl Deref for PluralRulesOptions

Source§

impl Deref for ProgressEvent

Source§

impl Deref for Proxy

Source§

impl Deref for PyBackedBytes

Source§

impl Deref for PyBackedStr

Source§

impl Deref for RangeError

Source§

impl Deref for ReadableStream

Source§

impl Deref for ReferenceError

Source§

impl Deref for RegExp

Source§

impl Deref for RegExpMatchArray

Source§

impl Deref for RelativeTimeFormat

Source§

impl Deref for RelativeTimeFormatOptions

Source§

impl Deref for RelativeTimeFormatPart

Source§

impl Deref for Request

Source§

impl Deref for RequestInit

Source§

impl Deref for ResolvedCollatorOptions

Source§

impl Deref for ResolvedDateTimeFormatOptions

Source§

impl Deref for ResolvedDisplayNamesOptions

Source§

impl Deref for ResolvedDurationFormatOptions

Source§

impl Deref for ResolvedListFormatOptions

Source§

impl Deref for ResolvedNumberFormatOptions

Source§

impl Deref for ResolvedPluralRulesOptions

Source§

impl Deref for ResolvedRelativeTimeFormatOptions

Source§

impl Deref for ResolvedSegmenterOptions

Source§

impl Deref for Response

Source§

impl Deref for ResponseInit

Source§

impl Deref for RuntimeError

Source§

impl Deref for SearchConfig

Source§

impl Deref for SegmentData

Source§

impl Deref for Segmenter

Source§

impl Deref for SegmenterOptions

Source§

impl Deref for Segments

Source§

impl Deref for SharedArrayBuffer

Source§

impl Deref for Storage

1.0.0 · Source§

impl Deref for String

Source§

impl Deref for Symbol

Source§

impl Deref for SyntaxError

Source§

impl Deref for Table

Source§

impl Deref for Tag

Source§

impl Deref for TextInfo

Source§

impl Deref for TranspositionTable

Source§

impl Deref for TypeError

Source§

impl Deref for Uint8Array

Source§

impl Deref for Uint8ClampedArray

Source§

impl Deref for Uint16Array

Source§

impl Deref for Uint32Array

Source§

impl Deref for Undefined

Source§

impl Deref for UriError

Source§

impl Deref for Url

Source§

impl Deref for UrlSearchParams

Source§

impl Deref for ValidOrNullMove

Source§

impl Deref for WebSocket

Source§

impl Deref for WeekInfo

Source§

impl Deref for Window

Source§

impl Deref for Worker

Source§

impl Deref for WorkerGlobalScope

Source§

impl Deref for WorkerOptions

Source§

impl<'a, T, A> Deref for alloc::vec::peek_mut::PeekMut<'a, T, A>
where A: Allocator,

1.36.0 · Source§

impl<'a> Deref for IoSlice<'a>

1.36.0 · Source§

impl<'a> Deref for IoSliceMut<'a>

Source§

impl<'py, T> Deref for Borrowed<'_, 'py, T>

Source§

type Target = Bound<'py, T>

Source§

impl<'py, T> Deref for Bound<'py, T>
where T: DerefToPyAny,

1.0.0 · Source§

impl<B> Deref for Cow<'_, B>
where B: ToOwned + ?Sized,

Source§

impl<K, V> Deref for Map<K, V>

Source§

impl<K, V> Deref for WeakMap<K, V>

Source§

impl<L, R> Deref for Either<L, R>
where L: Deref, R: Deref<Target = <L as Deref>::Target>,

Source§

type Target = <L as Deref>::Target

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

Source§

type Target = BR

1.33.0 (const: unstable) · Source§

impl<Ptr> Deref for Pin<Ptr>
where Ptr: Deref,

Source§

type Target = <Ptr as Deref>::Target

1.0.0 · Source§

impl<T, A> Deref for Arc<T, A>
where A: Allocator, T: ?Sized,

1.0.0 · Source§

impl<T, A> Deref for Box<T, A>
where A: Allocator, T: ?Sized,

1.12.0 · Source§

impl<T, A> Deref for alloc::collections::binary_heap::PeekMut<'_, T, A>
where T: Ord, A: Allocator,

1.0.0 · Source§

impl<T, A> Deref for Rc<T, A>
where A: Allocator, T: ?Sized,

Source§

impl<T, A> Deref for UniqueArc<T, A>
where A: Allocator, T: ?Sized,

Source§

impl<T, A> Deref for UniqueRc<T, A>
where A: Allocator, T: ?Sized,

1.0.0 (const: unstable) · Source§

impl<T, A> Deref for Vec<T, A>
where A: Allocator,

Source§

impl<T, F> Deref for DropGuard<T, F>
where F: FnOnce(T),

Source§

impl<T, F> Deref for once_cell::unsync::Lazy<T, F>
where F: FnOnce() -> T,

Source§

impl<T, F> Deref for once_cell::sync::Lazy<T, F>
where F: FnOnce() -> T,

1.80.0 · Source§

impl<T, F> Deref for LazyCell<T, F>
where F: FnOnce() -> T,

1.80.0 · Source§

impl<T, F> Deref for LazyLock<T, F>
where F: FnOnce() -> T,

Source§

impl<T, P> Deref for Punctuated<T, P>
where T: BinRead, P: BinRead,

Source§

impl<T, const CAP: usize> Deref for ArrayVec<T, CAP>

Source§

impl<T, const N: usize> Deref for MathVec<T, N>

1.0.0 (const: unstable) · Source§

impl<T> Deref for &T
where T: ?Sized,

1.0.0 (const: unstable) · Source§

impl<T> Deref for &mut T
where T: ?Sized,

Source§

impl<T> Deref for Array<T>

Source§

impl<T> Deref for ArrayTuple<T>
where T: JsTuple,

1.9.0 (const: unstable) · Source§

impl<T> Deref for AssertUnwindSafe<T>

Source§

impl<T> Deref for AsyncGenerator<T>

Source§

impl<T> Deref for AsyncIterator<T>

Source§

impl<T> Deref for BinaryMagic<T>

Source§

impl<T> Deref for Clamped<T>

Source§

impl<T> Deref for CustomDebug<T>

Source§

impl<T> Deref for Function<T>
where T: JsFunction,

Source§

impl<T> Deref for Generator<T>

Source§

impl<T> Deref for Iterator<T>

Source§

impl<T> Deref for IteratorNext<T>

Source§

impl<T> Deref for JsOption<T>

Source§

impl<T> Deref for JsStatic<T>
where T: FromWasmAbi + 'static,

Available on crate feature std and non-target feature atomics only.
1.20.0 (const: unstable) · Source§

impl<T> Deref for ManuallyDrop<T>
where T: ?Sized,

Source§

impl<T> Deref for std::sync::nonpoison::mutex::MappedMutexGuard<'_, T>
where T: ?Sized,

Source§

impl<T> Deref for std::sync::poison::mutex::MappedMutexGuard<'_, T>
where T: ?Sized,

Source§

impl<T> Deref for std::sync::nonpoison::rwlock::MappedRwLockReadGuard<'_, T>
where T: ?Sized,

Source§

impl<T> Deref for std::sync::poison::rwlock::MappedRwLockReadGuard<'_, T>
where T: ?Sized,

Source§

impl<T> Deref for std::sync::nonpoison::rwlock::MappedRwLockWriteGuard<'_, T>
where T: ?Sized,

Source§

impl<T> Deref for std::sync::poison::rwlock::MappedRwLockWriteGuard<'_, T>
where T: ?Sized,

Source§

impl<T> Deref for std::sync::nonpoison::mutex::MutexGuard<'_, T>
where T: ?Sized,

1.0.0 · Source§

impl<T> Deref for std::sync::poison::mutex::MutexGuard<'_, T>
where T: ?Sized,

Source§

impl<T> Deref for Object<T>

Source§

impl<T> Deref for PosValue<T>

Source§

impl<T> Deref for Promise<T>

Source§

impl<T> Deref for PromiseState<T>

Source§

impl<T> Deref for PropertyDescriptor<T>

Source§

impl<T> Deref for PyClassGuard<'_, T>
where T: PyClass,

Source§

impl<T> Deref for PyClassGuardMut<'_, T>
where T: PyClass<Frozen = False>,

Source§

impl<T> Deref for PyRef<'_, T>
where T: PyClass,

Source§

impl<T> Deref for PyRefMut<'_, T>
where T: PyClass<Frozen = False>,

Source§

impl<T> Deref for ReentrantLockGuard<'_, T>
where T: ?Sized,

1.0.0 (const: unstable) · Source§

impl<T> Deref for Ref<'_, T>
where T: ?Sized,

1.0.0 (const: unstable) · Source§

impl<T> Deref for RefMut<'_, T>
where T: ?Sized,

Source§

impl<T> Deref for std::sync::nonpoison::rwlock::RwLockReadGuard<'_, T>
where T: ?Sized,

1.0.0 · Source§

impl<T> Deref for std::sync::poison::rwlock::RwLockReadGuard<'_, T>
where T: ?Sized,

Source§

impl<T> Deref for std::sync::nonpoison::rwlock::RwLockWriteGuard<'_, T>
where T: ?Sized,

1.0.0 · Source§

impl<T> Deref for std::sync::poison::rwlock::RwLockWriteGuard<'_, T>
where T: ?Sized,

Source§

impl<T> Deref for SerdeWrapper<T>

Source§

impl<T> Deref for Set<T>

Source§

impl<T> Deref for ThinBox<T>
where T: ?Sized,

Source§

impl<T> Deref for WeakRef<T>

Source§

impl<T> Deref for WeakSet<T>

Source§

impl<U, const MUT: bool> Deref for PyClassGuardMap<'_, U, MUT>
where U: ?Sized,

Source§

impl<const CAP: usize> Deref for ArrayString<CAP>