Trait collections::borrow::Borrow
[−]
[src]
pub trait Borrow<Borrowed: ?Sized> {
fn borrow(&self) -> &Borrowed;
}A trait for borrowing data.
In general, there may be several ways to "borrow" a piece of data. The
typical ways of borrowing a type T`Tare` are &T`&T(a shared borrow) and` (a shared borrow) and &mut T`&mut T(a mutable borrow). But types like`
(a mutable borrow). But types like Vec<T>`Vecprovide additional kinds of borrows: the borrowed slices` provide additional kinds of
borrows: the borrowed slices &[T]`&[T]and` and &mut [T]`&mut [T]`.
When writing generic code, it is often desirable to abstract over all ways
of borrowing data from a given type. That is the role of the Borrow`Borrowtrait: if`
trait: if T: Borrow<U>`T: Borrow, then`, then &U`&Ucan be borrowed from` can be borrowed from &T`&T. A given type can be borrowed as multiple different types. In particular,`. A given
type can be borrowed as multiple different types. In particular, Vec<T>: Borrow<Vec<T>>`Vecand` and Vec<T>: Borrow<[T]>`Vec
Borrow`Borrowis very similar to, but different than,` is very similar to, but different than, AsRef`AsRef`. See
the book for more.
Required Methods
fn borrow(&self) -> &Borrowed
Immutably borrows from an owned value.
Examples
fn main() { use std::borrow::Borrow; fn check<T: Borrow<str>>(s: T) { assert_eq!("Hello", s.borrow()); } let s = "Hello".to_string(); check(s); let s = "Hello"; check(s); }use std::borrow::Borrow; fn check<T: Borrow<str>>(s: T) { assert_eq!("Hello", s.borrow()); } let s = "Hello".to_string(); check(s); let s = "Hello"; check(s);
Implementors
impl<T: ?Sized> Borrow<T> for Timpl<'a, T: ?Sized> Borrow<T> for &'a Timpl<'a, T: ?Sized> Borrow<T> for &'a mut Timpl<T: ?Sized> Borrow<T> for Box<T>impl<T> Borrow<T> for Rc<T>impl<T> Borrow<T> for Arc<T>impl<'a, B: ?Sized> Borrow<B> for Cow<'a, B> where B: ToOwned, B::Owned: 'aimpl<T> Borrow<[T]> for Vec<T>impl Borrow<str> for String