
Rust std::borrow::Borrow and BorrowMut: Designing APIs That Work with Owned and Borrowed Data
What Borrow and BorrowMut mean
Borrow<T> says: “this type can be viewed as a &T without changing its meaning.” BorrowMut<T> extends that idea to mutable access with &mut T.
The key idea is not just conversion, but semantic equivalence. If a type implements Borrow<str>, then its borrowed form should behave like a str for equality, ordering, and hashing.
Common examples from the standard library include:
String: Borrow<str>Vec<T>: Borrow<[T]>Box<T>: Borrow<T>
That means APIs can accept either owned or borrowed values while still working with the underlying borrowed representation.
Trait signatures
pub trait Borrow<Borrowed: ?Sized> {
fn borrow(&self) -> &Borrowed;
}
pub trait BorrowMut<Borrowed: ?Sized>: Borrow<Borrowed> {
fn borrow_mut(&mut self) -> &mut Borrowed;
}
The return type is a reference, not a conversion result. That distinction matters: Borrow is for zero-cost access to an equivalent view, not for transforming data.
Why Borrow is useful in API design
The most common use case is accepting keys or inputs in a generic way without forcing callers to allocate.
Consider a function that looks up a user by username. If the internal storage uses String, callers should still be able to pass &str:
use std::collections::HashMap;
struct UserDb {
users: HashMap<String, u32>,
}
impl UserDb {
fn get_user_id<Q>(&self, username: &Q) -> Option<&u32>
where
String: std::borrow::Borrow<Q>,
Q: std::hash::Hash + Eq + ?Sized,
{
self.users.get(username)
}
}
This pattern is common in standard collections. HashMap::get and BTreeMap::get accept borrowed lookup keys when the stored key type implements Borrow.
Practical benefit
Without Borrow, you might need separate methods:
get_user_id_str(&self, &str)get_user_id_string(&self, &String)
That duplicates logic and makes APIs harder to maintain. With Borrow, one method can serve both.
Borrow in standard collections
Rust collections use Borrow to support lookup by borrowed forms of keys.
Example: HashMap<String, V> looked up by &str
use std::collections::HashMap;
fn main() {
let mut map = HashMap::new();
map.insert("alice".to_string(), 10);
map.insert("bob".to_string(), 20);
assert_eq!(map.get("alice"), Some(&10));
assert_eq!(map.get("bob"), Some(&20));
}
Here, HashMap<String, V> can be queried with &str because String borrows as str, and str implements Hash and Eq compatibly with String.
Example: Vec<T> looked up by slice
fn contains_sequence(haystack: &[Vec<u8>], needle: &[u8]) -> bool {
haystack.iter().any(|item| item.borrow() == needle)
}
In practice, you often do not call borrow() explicitly in such cases because method resolution and deref coercions handle many common patterns. But the underlying concept is the same: the owned type can be viewed as its borrowed equivalent.
When to choose Borrow over AsRef
Borrow and AsRef are often confused, but they serve different purposes.
| Trait | Main purpose | Required semantic guarantees | Typical use |
|---|---|---|---|
AsRef<T> | Cheap reference conversion | None beyond returning &T | General-purpose APIs |
Borrow<T> | Equivalent borrowed view | Eq, Hash, and Ord must match the borrowed form | Map/set keys, lookup APIs |
BorrowMut<T> | Mutable borrowed view | Same equivalence expectations as Borrow | Mutating equivalent views |
Rule of thumb
- Use
AsRefwhen you just need a cheap reference conversion. - Use
Borrowwhen the borrowed form must behave identically for comparison and hashing. - Use
BorrowMutonly when mutable access to the borrowed representation is truly meaningful.
For example, a function that reads text can often use AsRef<str>. A hash map lookup should use Borrow<str>.
Designing generic functions with Borrow
A good Borrow-based API accepts a borrowed lookup key while remaining compatible with owned storage.
Example: a cache lookup
use std::borrow::Borrow;
use std::collections::HashMap;
use std::hash::Hash;
struct Cache<K, V> {
entries: HashMap<K, V>,
}
impl<K, V> Cache<K, V>
where
K: Eq + Hash,
{
fn get<Q>(&self, key: &Q) -> Option<&V>
where
K: Borrow<Q>,
Q: Eq + Hash + ?Sized,
{
self.entries.get(key)
}
}
This allows:
Cache<String, V>queried by&strCache<PathBuf, V>queried by&PathCache<Vec<u8>, V>queried by&[u8]
Why the bounds look like that
The lookup type Q must be hashable and comparable because the collection uses those traits to find entries. The stored key type K must be borrowable as Q so the collection can compare the borrowed view against the query.
This is the standard pattern for “owned storage, borrowed lookup.”
Common real-world examples
PathBuf and Path
Filesystem APIs often store owned paths but accept borrowed path references.
use std::path::{Path, PathBuf};
fn normalize(path: &Path) -> PathBuf {
path.to_path_buf()
}
fn main() {
let owned = PathBuf::from("/tmp/data");
let borrowed = Path::new("/tmp/data");
let a = normalize(&owned);
let b = normalize(borrowed);
assert_eq!(a, b);
}
PathBuf implements Borrow<Path>, which makes it suitable for lookup and API design where path ownership should remain flexible.
String and str
This is the most familiar case. String owns text, while str is the borrowed view. APIs that accept borrowed text should usually prefer &str or a Borrow<str>-based generic when lookup semantics matter.
Vec<T> and slices
Owned buffers often need borrowed access as slices. This is especially useful for binary data, protocol frames, or precomputed arrays.
Avoiding incorrect Borrow implementations
Borrow is not just “can return a reference.” It carries behavioral expectations. If you implement it manually, the borrowed form must be a true equivalent for equality and hashing.
Bad example: semantic mismatch
Suppose a type stores case-insensitive text but borrows as a case-sensitive str:
use std::borrow::Borrow;
struct CaseFolded(String);
impl Borrow<str> for CaseFolded {
fn borrow(&self) -> &str {
&self.0
}
}
This looks harmless, but it can break collection behavior if CaseFolded compares or hashes differently from str. A HashMap<CaseFolded, _> queried by &str may produce surprising results if the key’s Hash/Eq semantics do not match the borrowed view.
Best practices
- Implement
Borrowonly when the borrowed form is a true logical view of the same value. - Ensure
Hash,Eq, andOrdare consistent between owned and borrowed forms. - Prefer existing standard types that already implement
Borrowcorrectly. - If the relationship is only “cheap access,” use
AsRefinstead.
BorrowMut and mutable views
BorrowMut is less common than Borrow, but it is useful when a type wraps another value and you want to expose mutable access to the wrapped representation.
Example: wrapper around a buffer
use std::borrow::{Borrow, BorrowMut};
struct Buffer(Vec<u8>);
impl Borrow<[u8]> for Buffer {
fn borrow(&self) -> &[u8] {
&self.0
}
}
impl BorrowMut<[u8]> for Buffer {
fn borrow_mut(&mut self) -> &mut [u8] {
&mut self.0
}
}
This can be useful in abstractions that need to forward mutation to an inner buffer while preserving a stable wrapper type.
When not to use it
Avoid BorrowMut if mutation would violate invariants of the outer type. If the wrapper maintains metadata, cached state, or validation rules, exposing unrestricted mutable access to the inner value may make the type unsound at the API level, even if it compiles.
Choosing the right abstraction
| Need | Best choice |
|---|---|
| Cheap reference conversion only | AsRef<T> |
| Borrowed lookup in collections | Borrow<T> |
| Mutable access to an equivalent inner view | BorrowMut<T> |
| Accept owned or borrowed input ergonomically | impl AsRef<T> or Borrow-based generics |
| Preserve key semantics for hashing and equality | Borrow<T> |
Practical guidance
If you are designing a public API:
- Start with the narrowest trait that fits the use case.
- Use
Borrowfor lookup-oriented APIs and key types. - Use
AsReffor general conversion-style APIs. - Avoid over-generalizing with multiple trait bounds unless there is a concrete need.
Overly flexible signatures can make type inference harder and obscure the actual contract of the function.
A production-style example: index by borrowed key
Here is a more complete example of a registry that stores owned keys but supports borrowed queries.
use std::borrow::Borrow;
use std::collections::HashMap;
use std::hash::Hash;
struct Registry<K, V> {
items: HashMap<K, V>,
}
impl<K, V> Registry<K, V>
where
K: Eq + Hash,
{
fn new() -> Self {
Self {
items: HashMap::new(),
}
}
fn insert(&mut self, key: K, value: V) -> Option<V> {
self.items.insert(key, value)
}
fn get<Q>(&self, key: &Q) -> Option<&V>
where
K: Borrow<Q>,
Q: Eq + Hash + ?Sized,
{
self.items.get(key)
}
fn contains<Q>(&self, key: &Q) -> bool
where
K: Borrow<Q>,
Q: Eq + Hash + ?Sized,
{
self.items.contains_key(key)
}
}
fn main() {
let mut registry = Registry::<String, usize>::new();
registry.insert("alpha".to_string(), 1);
registry.insert("beta".to_string(), 2);
assert!(registry.contains("alpha"));
assert_eq!(registry.get("beta"), Some(&2));
}
This pattern scales well because it keeps storage ownership separate from query ergonomics. Callers can use borrowed values, while the registry still owns its keys.
Best practices for Borrow-based APIs
- Prefer
Borrowfor map/set keys and other equality-based lookups. - Keep the borrowed form semantically identical to the owned form.
- Use
?Sizedon the borrowed type parameter when you want to support slices and strings. - Do not implement
Borrowjust to avoid writingAsRef; the guarantees are stronger. - Document lookup behavior clearly, especially if custom key types are involved.
- Test borrowed lookups explicitly with both owned and borrowed inputs.
A good mental model is: Borrow is for “same value, different ownership,” not “convert to something similar.”