Rust Reference ยท Core Traits
The Borrow and ToOwned traits
Reference for the Rust Borrow, BorrowMut and ToOwned traits: why HashMap<String, V> accepts &str lookups, how ToOwned powers Cow, and Borrow vs AsRef.
Borrow<B> says "an owned value of this type can be viewed as a B, and the view behaves identically for equality, ordering and hashing". String borrows as str, Vec<T> as [T], Box<T> as T. Collections use it to let you look things up with the cheap borrowed form: a HashMap<String, V> accepts &str in get.
ToOwned goes in the other direction. It turns a borrowed value into an owned one, and is the generalization of Clone to unsized types: str becomes String, [T] becomes Vec<T>. It is the engine behind Cow.
let mut m: HashMap<String, i32> = HashMap::new(); m.insert("a".to_string(), 1); m.get("a"); // &str, not &String
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
pub trait Borrow<Borrowed: ?Sized> { fn borrow(&self) -> &Borrowed; } pub trait BorrowMut<Borrowed: ?Sized>: Borrow<Borrowed> { fn borrow_mut(&mut self) -> &mut Borrowed; } pub trait ToOwned { type Owned: Borrow<Self>; fn to_owned(&self) -> Self::Owned; }
| Name | Description |
|---|---|
Borrowed |
The borrowed view type: str, [T], Path, or T itself. Every T implements Borrow<T>. |
Owned |
The owned type produced by to_owned, such as String for str. |
Returns: borrow gives a reference; to_owned gives a new owned value (it allocates for str and [T]).
Usage notes
- The contract is about equality.
x.borrow() == y.borrow()must agree withx == y, andHashandOrdmust agree too.HashMap::get<Q>(&self, k: &Q) where K: Borrow<Q>, Q: Hash + Eq + ?Sizeddepends on this. - Do not implement
Borrowjust for convenience. A wrapper that compares case-insensitively must notBorrow<str>as the raw text. UseAsRefwhen the view does not promise matching behavior. - Ambiguity:
StringimplementsBorrow<str>andBorrow<String>, so a bares.borrow()often needs a type annotation. Calls likemap.get("a")infer correctly. ToOwnedversusClone: for sized typesto_owned()isclone()(everyClonetype getsToOwned). Forstr,[T],Path,OsStrandCStr, onlyToOwnedcan give an owned value, since you cannot clone an unsized value.to_owned()on a literal ("x".to_owned()) is the same asto_string()orString::from; pick one style and keep it.Cow<'a, B>holds either&'a BorB::Owned. It avoids allocating in the common unchanged case.to_mut()clones on first write;into_owned()ends with an owned value. See Cow and Borrow.- Tuples and compound keys do not borrow as tuples of borrowed forms:
HashMap<(String, String), V>cannot be queried with(&str, &str). Use a struct key with a customBorrow, nested maps orhashbrown's raw entry APIs. BorrowMutis rarely used directly. PreferAsMutor ordinary&mutparameters.
Related
AsRefandAsMut,Hash,Clone,DerefandDerefMut- Lessons: Cow and Borrow, HashMap, Strings