Trait | URL |
---|---|
Into |
std::convert::Into |
TryInto |
std::convert::TryInto |
pub trait Into<D> {
fn into(self) -> D;
}
Self
implies source typeS
;- method
into()
performs the conversion;
Trait Into
is used to convert value from source type S
on which it is implemented to destination type D
.
Trait Into
must not fail. If the conversion can fail, use TryInto
.
Notes:
- The trait
Into
doesn't automatically implementsFrom
(asFrom
does). Therefore, you should always try to implementFrom
and then fall back toInto
ifFrom
can’t be implemented. - 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, the code below will fail in Rust prior 1.41 version:
struct Wrapper<T>(Vec<T>);
impl<T> From<Wrapper<T>> for Vec<T> {
fn from(w: Wrapper<T>) -> Vec<T> {
w.0
}
}
To bypass this, you could implement Into
directly:
struct Wrapper<T>(Vec<T>);
impl<T> Into<Vec<T>> for Wrapper<T> {
fn into(self) -> Vec<T> {
self.0
}
}
pub trait TryInto<T> {
type Error;
fn try_into(self) -> Result<T, Self::Error>;
}
TryInto<T>
returns Result<T, E>
.