Rust Conversion traits Borrow, BorrowMut and ToOwned


Example

The std::borrow::Borrow and std::borrow::BorrowMut traits are used to treat borrowed types like owned types. For types A and B,

impl Borrow<B> for A

indicates that a borrowed A may be used where a B is desired. For instance, std::collections::HashMap.get() uses Borrow for its get() method, allowing a HashMap with keys of A to be indexed with a &B.


On the other hand, std::borrow::ToOwned implements the reverse relationship.

Thus, with the aforementioned types A and B one can implement:

impl ToOwned for B

Note: while A can implement Borrow<T> for multiple distinct types T, B can only implement ToOwned once.