ToOwned::to_owned and Borrow::borrow
pub trait ToOwned {
type Owned: Borrow<Self>;
fn to_owned(&self) -> Self::Owned;
}
pub trait Borrow<Borrowed>
where
Borrowed: ?Sized
{
fn borrow(&self) -> &Borrowed;
}Create an owned value from a borrow, or borrow an owned value as its borrowed form.
| Parameter | Description |
|---|---|
self | The borrowed view for to_owned, or the owned value for borrow. |
Returns: to_owned returns Owned (String for str, Vec<T> for [T]). borrow returns a shared reference to the borrowed type.
- to_owned on str allocates a new String. It is not a way to avoid a copy; it is how you take ownership of a copy.
- HashMap lookup with borrowed keys is documented on the HashMap page. This page only shows the traits that make that lookup possible.
use std::borrow::{Borrow, ToOwned};
fn main() {
let borrowed: &str = "port";
let owned: String = borrowed.to_owned();
let as_str: &str = owned.borrow();
println!("borrowed_key={as_str}");
}Expected output
borrowed_key=portRelated: From, Into, AsRef, and AsMut, HashMap key lookup, str and String