As title, specifically, consider this code snippet that defines a trait known as Form<T>
:
trait Form<T>
where
T: ?Sized,
{
fn form(&self) -> T;
}
Also, consider this blanket implementation:
use std::borrow::{Borrow, ToOwned};
impl<T, U> Form<T> for U
where
T: ToOwned<Owned = T>,
U: Borrow<T>,
{
fn form(&self) -> T {
<T as ToOwned>::to_owned(<U as Borrow<T>>::borrow(self))
}
}
I do think perhaps we should have this trait in the standard library but I don't understand why we don't.
Summary
Basically, a type T
that implements Form<U>
is saying the following:
A value of type
T
has sufficient information to 'create' / 'form' a value of typeU
if it implementsForm<U>
.
Advantages of this Form<T>
Use Cases
I can imagine these use cases.
- We have
Configurations
struct that we can use to createExecutor
and whatever other structs. - Different crates can implement
Form<StructDefinedInMyCrate> for StructDefinedInOtherCrates
, in whichStructDefinedInMyCrate
is a local type andStructDefinedInOtherCrates
is a foreign type.
Comparing with ToOwned
ToOwned
is not generic, that is given a typeT
, by implementingToOwned<Owned = U>
, it means given a&T
, only aU
can be gotten from it. However, sometimes, we may want&T
to be capable of producing more thanU
value.
Comparing to AsRef<T>
(as AsMut<T>
)
Form<T>
can be seen as a restriction ofAsRef<T>
wherebyAsRef<T>
returns a&T
,Form<T>
is restricting it to return an ownedT
. Similarly forAsMut<T>
.
Comparing to Into<T>
(and From<U>
where U: Into<T>
)
- The
From
andInto
traits areequivalent-conversion
traits as their methods consumeself
.Form<T>
does not consumeself
.
Comparing to Borrow<T>
Form<T>
can be seen as a restricted (since an owned value is more restrictive than a referred value) version ofBorrow<T>
. Whereimpl Borrow<T> for U
is roughly saying you can get a&T
cheaply from aU
,impl Form<T> for U
is saying you can get an ownedT
'cheaply' from aU
.
Hence, the question is:
Why is a trait like
Form<T>
not in the standard library?
Thank you.