Skip to content
Tutorials Center
My learning

Topics

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.

Rust
let mut m: HashMap<String, i32> = HashMap::new();
m.insert("a".to_string(), 1);
m.get("a"); // &str, not &String

Try it

Rust Lookups with the borrowed form

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.

Rust ToOwned and Cow

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

Rust
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 with x == y, and Hash and Ord must agree too. HashMap::get<Q>(&self, k: &Q) where K: Borrow<Q>, Q: Hash + Eq + ?Sized depends on this.
  • Do not implement Borrow just for convenience. A wrapper that compares case-insensitively must not Borrow<str> as the raw text. Use AsRef when the view does not promise matching behavior.
  • Ambiguity: String implements Borrow<str> and Borrow<String>, so a bare s.borrow() often needs a type annotation. Calls like map.get("a") infer correctly.
  • ToOwned versus Clone: for sized types to_owned() is clone() (every Clone type gets ToOwned). For str, [T], Path, OsStr and CStr, only ToOwned can give an owned value, since you cannot clone an unsized value.
  • to_owned() on a literal ("x".to_owned()) is the same as to_string() or String::from; pick one style and keep it.
  • Cow<'a, B> holds either &'a B or B::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 custom Borrow, nested maps or hashbrown's raw entry APIs.
  • BorrowMut is rarely used directly. Prefer AsMut or ordinary &mut parameters.