pub trait AsRef<T:PointeeSized>:PointeeSized { // Required method fnas_ref(&self) ->&T;}Expand description
Used to do a cheap reference-to-reference conversion.
This trait is similar toAsMut which is used for converting between mutable references.If you need to do a costly conversion it is better to implementFrom with type&T or write a custom function.
§Relation toBorrow
AsRef has the same signature asBorrow, butBorrow is different in a few aspects:
- Unlike
AsRef,Borrowhas a blanket impl for anyT, and can be used to accept eithera reference or a value. (See also note onAsRef’s reflexibility below.) Borrowalso requires thatHash,EqandOrdfor a borrowed value areequivalent to those of the owned value. For this reason, if you want toborrow only a single field of a struct you can implementAsRef, but notBorrow.
Note: This trait must not fail. If the conversion can fail, use adedicated method which returns anOption<T> or aResult<T, E>.
§Generic Implementations
AsRef auto-dereferences if the inner type is a reference or a mutable reference(e.g.:foo.as_ref() will work the same iffoo has type&mut Foo or&&mut Foo).
Note that due to historic reasons, the above currently does not hold generally for alldereferenceable types, e.g.foo.as_ref() willnot work the same asBox::new(foo).as_ref(). Instead, many smart pointers provide anas_ref implementation whichsimply returns a reference to thepointed-to value (but do not perform a cheapreference-to-reference conversion for that value). However,AsRef::as_ref should not beused for the sole purpose of dereferencing; instead‘Deref coercion’ can be used:
Types which implementDeref should consider implementingAsRef<T> as follows:
impl<T> AsRef<T>forSomeTypewhereT:?Sized, <SomeTypeasDeref>::Target: AsRef<T>,{fnas_ref(&self) ->&T {self.deref().as_ref() }}§Reflexivity
Ideally,AsRef would be reflexive, i.e. there would be animpl<T: ?Sized> AsRef<T> for Twithas_ref simply returning its argument unchanged.Such a blanket implementation is currentlynot provided due to technical restrictions ofRust’s type system (it would be overlapping with another existing blanket implementation for&T where T: AsRef<U> which allowsAsRef to auto-dereference, see “Generic Implementations”above).
A trivial implementation ofAsRef<T> for T must be added explicitly for a particular typeTwhere needed or desired. Note, however, that not all types fromstd contain such animplementation, and those cannot be added by external code due to orphan rules.
§Examples
By using trait bounds we can accept arguments of different types as long as they can beconverted to the specified typeT.
For example: By creating a generic function that takes anAsRef<str> we express that wewant to accept all references that can be converted to&str as an argument.Since bothString and&str implementAsRef<str> we can accept both as input argument.