pub trait Into<T>: Sized {
// Required method
fn into(self) -> T;
}
Expand description
A value-to-value conversion that consumes the input value. The
opposite of From
.
One should avoid implementing Into
and implement From
instead.
Implementing From
automatically provides one with an implementation of Into
thanks to the blanket implementation in the standard library.
Prefer using Into
over From
when specifying trait bounds on a generic function
to ensure that types that only implement Into
can be used as well.
Note: This trait must not fail. If the conversion can fail, use TryInto
.
§Generic Implementations
From
<T> for U
impliesInto<U> for T
Into
is reflexive, which means thatInto<T> for T
is implemented
§Implementing Into
for conversions to external types in old versions of Rust
Prior to Rust 1.41, if the destination type was not part of the current crate
then you couldn’t implement From
directly.
For example, take this code:
struct Wrapper<T>(Vec<T>);
impl<T> From<Wrapper<T>> for Vec<T> {
fn from(w: Wrapper<T>) -> Vec<T> {
w.0
}
}
This will fail to compile in older versions of the language because Rust’s orphaning rules used to be a little bit more strict. To bypass this, you could implement