Rust Conversion traits Borrow, BorrowMut and ToOwned

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

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.



Got any Rust Question?