trait

Borrow — equivalent borrowed representation

Expose a borrowed representation with matching equality, ordering and hashing semantics whenever those operations are implemented. A String and its str view meet this requirement. Borrow is stronger than merely providing access to an inner field. Expected stdout (not executed): Some(3) Common mistake: Implementing Borrow<str> for a case-insensitive key with ordinary case-sensitive str hashing.

Formal Syntax & Structure

rust syntaxrust
pub trait Borrow<Borrowed: ?Sized> { fn borrow(&self) -> &Borrowed; }

Working Example

Example Snippetrust
fn main() {    use std::{borrow::Borrow, collections::HashMap};    let key = String::from("tea");    let view: &str = key.borrow();    let m = HashMap::from([(String::from("tea"), 3)]);    println!("{:?}", m.get(view));}
Rust Reference