pub trait ToOwned {
type Owned;
// Required method
fn to_owned(&self) -> Self::Owned;
}
Expand description
Convert to owned.
This works similarly to ToOwned
with a few
relaxed constaints. It is recommended that you use
to_owned
instead of importing this trait.
What about std::borrow::ToOwned
?
std::borrow::ToOwned
a trait which requires that the resulting Owned
type can be borrowed back into a reference of itself. This can’t be
implemented for compound borrowing (See
borrowme::Borrow
). So because we can’t implement
std::borrow::Borrow<Self>
, we can’t implemented
std::borrow::ToOwned
either.
To showcase this, let’s try to implement std::borrow::ToOwned
for a type
which has a lifetime parameter:
struct Word<'a>(&'a str);
struct OwnedWord(String);
impl ToOwned for Word<'_> {
type Owned = OwnedWord;
fn to_owned(&self) -> OwnedWord {
OwnedWord(String::from(self.0))
}
}
error[E0277]: the trait bound `OwnedWord: std::borrow::Borrow<Word<'_>>` is not satisfied
--> src/lib.rs:27:18
|
11 | type Owned = OwnedWord;
| ^^^^^^^^^ the trait `std::borrow::Borrow<Word<'_>>` is not implemented for `OwnedWord`
So in this crate we define a different ToOwned
trait which does not
require the produced value to be Borrow<Self>
.
With this, we can implement the conversion:
use borrowme::ToOwned;
impl ToOwned for Word<'_> {
type Owned = OwnedWord;
fn to_owned(&self) -> OwnedWord {
OwnedWord(self.0.to_string())
}
}