In Rust, `Borrow<str>` and `AsRef<str>` share a method signature, so why may a case-insensitive name type implement only `AsRef<str>`?
answer
- same signature, different promise
- maps look keys up through it
- Eq, Ord and Hash must agree
- a logic error, not UB
basics
~20 sBorrow adds a contract AsRef lacks: Eq, Ord and Hash of the borrowed view must match the owned value's, because maps look keys up through it. A case-insensitive key compares differently from str, so Borrow<str> would make lookups silently miss.
solid answer
~40 s`HashMap::get` is generic as `get<Q>(&self, k: &Q) where K: Borrow<Q>, Q: Hash + Eq`: it hashes the `&str` you pass and compares it with `key.borrow()`. That only works if a key hashes and compares exactly like its borrowed form, which is what the `Borrow` docs require ("`Eq`, `Ord` and `Hash` must be equivalent for borrowed and owned values"). A name type that compares ignoring ASCII case disagrees with `str`, so a `Borrow<str>` impl makes `get("Ana")` miss or hit the wrong entry. The compiler cannot check this; the std map docs call such a violation a logic error with unspecified results but no undefined behaviour. `AsRef<str>` carries no such contract, so it is the right way to expose the text.
code
rust · 32 linesuse std::borrow::Borrow;
use std::cmp::Ordering;
use std::collections::BTreeMap;
// A key that orders names ignoring ASCII case...
#[derive(Debug, Eq)]
struct Name(String);
impl PartialEq for Name {
fn eq(&self, o: &Self) -> bool { self.0.eq_ignore_ascii_case(&o.0) }
}
impl Ord for Name {
fn cmp(&self, o: &Self) -> Ordering {
self.0.to_ascii_lowercase().cmp(&o.0.to_ascii_lowercase())
}
}
impl PartialOrd for Name {
fn partial_cmp(&self, o: &Self) -> Option<Ordering> { Some(self.cmp(o)) }
}
// ...but claims to borrow as str, whose Ord is case-sensitive. Contract broken.
impl Borrow<str> for Name {
fn borrow(&self) -> &str { &self.0 }
}
fn main() {
let mut scores = BTreeMap::new();
for n in ["apple", "Banana", "cherry"] {
scores.insert(Name(n.to_string()), n.len());
}
println!("{:?}", scores.get("cherry")); // Some(6)
println!("{:?}", scores.get("Banana")); // None: the exact key is in the map
}go deeper
Recall that Borrow is why a map keyed by String can be searched with a &str, and that AsRef is the looser of the two traits.
Explain the Eq, Ord and Hash agreement Borrow demands and why AsRef can lend a single field while Borrow cannot.
Diagnose a map that misses keys it holds by checking key types' Borrow impls against their Hash, Eq and Ord, and expect a logic error, not UB.
When custom key types with their own equality spread through a codebase, prefer normalising the key on insert over clever Borrow impls nobody can verify.
## Same signature, different promise The two traits look interchangeable: ```rust pub trait AsRef<T: ?Sized> { fn as_ref(&self) -> &T; } pub trait Borrow<Borrowed: ?Sized> { fn borrow(&self) -> &Borrowed; } ``` Both lend a reference to some other type. The difference is in the documentation, and it is a contract the compiler cannot verify: | | `AsRef<T>` | `Borrow<T>` | |---|---|---| | Purpose | a cheap view of related data | the value **is** a `T` in another representation | | `Eq`, `Ord`, `Hash` must match the owned value | no | **yes** | | Blanket impl for every `T` (reflexive) | no | yes, plus `&T` and `&mut T` | | May lend a single field of a struct | yes | no | | Typical implementors | `String: AsRef<[u8]>`, `AsRef<OsStr>`, `AsRef<Path>` | `String: Borrow<str>`, `Vec<T>: Borrow<[T]>`, `PathBuf: Borrow<Path>`, `Box<T>: Borrow<T>` | The `Borrow` docs spell the rule out: "`Eq`, `Ord` and `Hash` must be equivalent for borrowed and owned values: `x.borrow() == y.borrow()` should give the same result as `x == y`." They add that if generic code merely needs some reference to a related type, `AsRef` is often better "as more types can safely implement it". ## Why maps depend on the promise The `Borrow` documentation uses `HashMap` as its worked example. Simplified: ```rust pub fn get<Q>(&self, k: &Q) -> Option<&V> where K: Borrow<Q>, Q: Hash + Eq + ?Sized, ``` On insert, the map hashes the **owned** key `K`. On lookup by `&Q`, it hashes the **borrowed** form `Q` and compares it with `key.borrow()`. Those two hashes must land in the same bucket, and the comparison must agree with `K`'s own `Eq`. This is what lets a `HashMap<String, V>` be searched with a `&str` without building a `String`; the map side of that story is covered with hash maps. `BTreeMap` relies on `Ord` the same way. ## What breaks when the promise is false Take a `Name(String)` whose comparisons ignore ASCII case — the idea behind the `Borrow` docs' own `CaseInsensitiveString` example, which ignores case in `PartialEq` and `Hash`. It *can* hand out `&str` from its field, but `str` hashes and orders its bytes exactly. The docs conclude that such a type "must not, in fact, implement `Borrow<str>`" and should offer `AsRef<str>` instead. If it implements `Borrow<str>` anyway: 1. The code compiles; nothing in the type system ties `borrow()` to `Hash` or `Ord`. 2. Lookups by `&str` use `str`'s hash and order, while the map was organised by `Name`'s, so `get` can return `None` for a key that is present — in the example below, `get("Banana")` misses an entry spelled exactly `"Banana"`. 3. The result is a **logic error**, not undefined behaviour. The `HashMap` docs say the behaviour resulting from a logic error "is not specified, but will be encapsulated to the `HashMap` that observed the logic error and not result in undefined behavior", and list panics, incorrect results, aborts, memory leaks and non-termination as possibilities. The `BTreeMap` example is deterministic: the tree stores `apple, Banana, cherry` in case-insensitive order, and a lookup with `str`'s case-sensitive order stops at `apple` because `"Banana" < "apple"` byte-wise. ## Borrow's extra impls and ToOwned `Borrow` also has blanket impls that `AsRef` lacks: `impl<T: ?Sized> Borrow<T> for T`, plus impls for `&T` and `&mut T`. A bound `K: Borrow<i32>` therefore accepts both `i32` and `&i32`, which `AsRef<i32>` would not. `ToOwned` is the reverse direction, and it is defined in terms of `Borrow`: - `type Owned: Borrow<Self>;` — whatever `to_owned()` returns must borrow back as the original, under the same contract. - `str::to_owned()` returns `String`, `[T]::to_owned()` returns `Vec<T>`, and every `T: Clone` gets `ToOwned` with `Owned = T` through a blanket impl. That pairing is what clone-on-write smart pointers build on, which is covered with `Cow`. ## Choosing between them - Implement `Borrow<T>` only when your type's `Eq`, `Ord` and `Hash` are exactly `T`'s — typically an owning wrapper around `T` itself. - Implement `AsRef<T>` for any cheap view, including one field or a type with its own comparison rules. - In generic code, require `Borrow<Q>` when you will hash or compare through the reference, and `AsRef<T>` when you only read through it. When a map "loses" keys it visibly holds, check these in order: - whether the key type implements `Borrow` for the type used in lookups; - whether its `Hash`, `Eq` and `Ord` impls are hand-written rather than derived; - whether any of them normalise the data (case, whitespace, rounding) that the borrowed type does not. The usual repair is to drop the `Borrow` impl and normalise the text once, when the key is built, so the owned key and the lookup string agree by construction.
- Is a `Borrow` impl whose `Hash` disagrees with the owned type undefined behaviour?No. It is a logic error. The `HashMap` docs say the resulting behaviour is unspecified but confined to that map and never undefined behaviour; it may show up as wrong results, panics, aborts, leaks or non-termination. Safe code cannot cause UB this way.
- How does `ToOwned` relate to `Borrow`?`ToOwned` declares `type Owned: Borrow<Self>`, so the owned form must borrow back as the original under `Borrow`'s contract. That is why `str::to_owned()` returns a `String` and `[T]::to_owned()` a `Vec<T>`; any `T: Clone` gets `ToOwned` with `Owned = T` for free.
- Borrow and AsRef are interchangeable because their methods have the same signature.
- The compiler checks that a Borrow impl's Hash agrees with the owned type's.
- A Borrow impl whose Hash disagrees causes undefined behaviour in HashMap.
- Implementing Borrow<str> is harmless whenever borrow() returns the correct text.
- AsRef also requires Eq, Ord and Hash to match the target type.