Skip to content

Latest commit

 

History

History
84 lines (67 loc) · 1.9 KB

Into-TryInto.md

File metadata and controls

84 lines (67 loc) · 1.9 KB

Table of contents


URLs

Trait URL
Into std::convert::Into
TryInto std::convert::TryInto

Trait Into

Declaration

pub trait Into<D> {
    fn into(self) -> D;
}
  • Self implies source type S;
  • method into() performs the conversion;

In a nutshell

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 implements From (as From does). Therefore, you should always try to implement From and then fall back to Into if From 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.

Example

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
    }
}

Trait TryInto

Declaration

pub trait TryInto<T> {
    type Error;
    fn try_into(self) -> Result<T, Self::Error>;
}

In a nutshell

TryInto<T> returns Result<T, E>.