1 //! A module for working with borrowed data.
3 #![stable(feature = "rust1", since = "1.0.0")]
5 /// A trait for borrowing data.
7 /// In Rust, it is common to provide different representations of a type for
8 /// different use cases. For instance, storage location and management for a
9 /// value can be specifically chosen as appropriate for a particular use via
10 /// pointer types such as [`Box<T>`] or [`Rc<T>`]. Beyond these generic
11 /// wrappers that can be used with any type, some types provide optional
12 /// facets providing potentially costly functionality. An example for such a
13 /// type is [`String`] which adds the ability to extend a string to the basic
14 /// [`str`]. This requires keeping additional information unnecessary for a
15 /// simple, immutable string.
17 /// These types provide access to the underlying data through references
18 /// to the type of that data. They are said to be ‘borrowed as’ that type.
19 /// For instance, a [`Box<T>`] can be borrowed as `T` while a [`String`]
20 /// can be borrowed as `str`.
22 /// Types express that they can be borrowed as some type `T` by implementing
23 /// `Borrow<T>`, providing a reference to a `T` in the trait’s
24 /// [`borrow`] method. A type is free to borrow as several different types.
25 /// If it wishes to mutably borrow as the type – allowing the underlying data
26 /// to be modified, it can additionally implement [`BorrowMut<T>`].
28 /// Further, when providing implementations for additional traits, it needs
29 /// to be considered whether they should behave identical to those of the
30 /// underlying type as a consequence of acting as a representation of that
31 /// underlying type. Generic code typically uses `Borrow<T>` when it relies
32 /// on the identical behavior of these additional trait implementations.
33 /// These traits will likely appear as additional trait bounds.
35 /// In particular `Eq`, `Ord` and `Hash` must be equivalent for
36 /// borrowed and owned values: `x.borrow() == y.borrow()` should give the
37 /// same result as `x == y`.
39 /// If generic code merely needs to work for all types that can
40 /// provide a reference to related type `T`, it is often better to use
41 /// [`AsRef<T>`] as more types can safely implement it.
43 /// [`BorrowMut<T>`]: BorrowMut
44 /// [`Box<T>`]: ../../std/boxed/struct.Box.html
45 /// [`Mutex<T>`]: ../../std/sync/struct.Mutex.html
46 /// [`Rc<T>`]: ../../std/rc/struct.Rc.html
47 /// [`String`]: ../../std/string/struct.String.html
48 /// [`borrow`]: Borrow::borrow
52 /// As a data collection, [`HashMap<K, V>`] owns both keys and values. If
53 /// the key’s actual data is wrapped in a managing type of some kind, it
54 /// should, however, still be possible to search for a value using a
55 /// reference to the key’s data. For instance, if the key is a string, then
56 /// it is likely stored with the hash map as a [`String`], while it should
57 /// be possible to search using a [`&str`][`str`]. Thus, `insert` needs to
58 /// operate on a `String` while `get` needs to be able to use a `&str`.
60 /// Slightly simplified, the relevant parts of `HashMap<K, V>` look like
64 /// use std::borrow::Borrow;
65 /// use std::hash::Hash;
67 /// pub struct HashMap<K, V> {
68 /// # marker: ::std::marker::PhantomData<(K, V)>,
72 /// impl<K, V> HashMap<K, V> {
73 /// pub fn insert(&self, key: K, value: V) -> Option<V>
74 /// where K: Hash + Eq
76 /// # unimplemented!()
80 /// pub fn get<Q>(&self, k: &Q) -> Option<&V>
83 /// Q: Hash + Eq + ?Sized
85 /// # unimplemented!()
91 /// The entire hash map is generic over a key type `K`. Because these keys
92 /// are stored with the hash map, this type has to own the key’s data.
93 /// When inserting a key-value pair, the map is given such a `K` and needs
94 /// to find the correct hash bucket and check if the key is already present
95 /// based on that `K`. It therefore requires `K: Hash + Eq`.
97 /// When searching for a value in the map, however, having to provide a
98 /// reference to a `K` as the key to search for would require to always
99 /// create such an owned value. For string keys, this would mean a `String`
100 /// value needs to be created just for the search for cases where only a
101 /// `str` is available.
103 /// Instead, the `get` method is generic over the type of the underlying key
104 /// data, called `Q` in the method signature above. It states that `K`
105 /// borrows as a `Q` by requiring that `K: Borrow<Q>`. By additionally
106 /// requiring `Q: Hash + Eq`, it signals the requirement that `K` and `Q`
107 /// have implementations of the `Hash` and `Eq` traits that produce identical
110 /// The implementation of `get` relies in particular on identical
111 /// implementations of `Hash` by determining the key’s hash bucket by calling
112 /// `Hash::hash` on the `Q` value even though it inserted the key based on
113 /// the hash value calculated from the `K` value.
115 /// As a consequence, the hash map breaks if a `K` wrapping a `Q` value
116 /// produces a different hash than `Q`. For instance, imagine you have a
117 /// type that wraps a string but compares ASCII letters ignoring their case:
120 /// pub struct CaseInsensitiveString(String);
122 /// impl PartialEq for CaseInsensitiveString {
123 /// fn eq(&self, other: &Self) -> bool {
124 /// self.0.eq_ignore_ascii_case(&other.0)
128 /// impl Eq for CaseInsensitiveString { }
131 /// Because two equal values need to produce the same hash value, the
132 /// implementation of `Hash` needs to ignore ASCII case, too:
135 /// # use std::hash::{Hash, Hasher};
136 /// # pub struct CaseInsensitiveString(String);
137 /// impl Hash for CaseInsensitiveString {
138 /// fn hash<H: Hasher>(&self, state: &mut H) {
139 /// for c in self.0.as_bytes() {
140 /// c.to_ascii_lowercase().hash(state)
146 /// Can `CaseInsensitiveString` implement `Borrow<str>`? It certainly can
147 /// provide a reference to a string slice via its contained owned string.
148 /// But because its `Hash` implementation differs, it behaves differently
149 /// from `str` and therefore must not, in fact, implement `Borrow<str>`.
150 /// If it wants to allow others access to the underlying `str`, it can do
151 /// that via `AsRef<str>` which doesn’t carry any extra requirements.
153 /// [`Hash`]: crate::hash::Hash
154 /// [`HashMap<K, V>`]: ../../std/collections/struct.HashMap.html
155 /// [`String`]: ../../std/string/struct.String.html
156 #[stable(feature = "rust1", since = "1.0.0")]
157 pub trait Borrow<Borrowed: ?Sized> {
158 /// Immutably borrows from an owned value.
163 /// use std::borrow::Borrow;
165 /// fn check<T: Borrow<str>>(s: T) {
166 /// assert_eq!("Hello", s.borrow());
169 /// let s = "Hello".to_string();
177 #[stable(feature = "rust1", since = "1.0.0")]
178 fn borrow(&self) -> &Borrowed;
181 /// A trait for mutably borrowing data.
183 /// As a companion to [`Borrow<T>`] this trait allows a type to borrow as
184 /// an underlying type by providing a mutable reference. See [`Borrow<T>`]
185 /// for more information on borrowing as another type.
187 /// [`Borrow<T>`]: Borrow
188 #[stable(feature = "rust1", since = "1.0.0")]
189 pub trait BorrowMut<Borrowed: ?Sized>: Borrow<Borrowed> {
190 /// Mutably borrows from an owned value.
195 /// use std::borrow::BorrowMut;
197 /// fn check<T: BorrowMut<[i32]>>(mut v: T) {
198 /// assert_eq!(&mut [1, 2, 3], v.borrow_mut());
201 /// let v = vec![1, 2, 3];
205 #[stable(feature = "rust1", since = "1.0.0")]
206 fn borrow_mut(&mut self) -> &mut Borrowed;
209 #[stable(feature = "rust1", since = "1.0.0")]
210 impl<T: ?Sized> Borrow<T> for T {
211 fn borrow(&self) -> &T {
216 #[stable(feature = "rust1", since = "1.0.0")]
217 impl<T: ?Sized> BorrowMut<T> for T {
218 fn borrow_mut(&mut self) -> &mut T {
223 #[stable(feature = "rust1", since = "1.0.0")]
224 impl<T: ?Sized> Borrow<T> for &T {
225 fn borrow(&self) -> &T {
230 #[stable(feature = "rust1", since = "1.0.0")]
231 impl<T: ?Sized> Borrow<T> for &mut T {
232 fn borrow(&self) -> &T {
237 #[stable(feature = "rust1", since = "1.0.0")]
238 impl<T: ?Sized> BorrowMut<T> for &mut T {
239 fn borrow_mut(&mut self) -> &mut T {