pub trait Into<T> { fn into(self) -> T; }
A value-to-value conversion that consumes the input value. The opposite of From
.
One should only implement Into
if a conversion to a type outside the current crate is required. Otherwise one should always prefer implementing From
over Into
because implementing From
automatically provides one with a implementation of Into
thanks to the blanket implementation in the standard library. From
cannot do these type of conversions because of Rust's orphaning rules.
Note: This trait must not fail. If the conversion can fail, use TryInto
.
From
<T> for U
implies Into<U> for T
Into
is reflexive, which means that Into<T> for T
is implementedInto
for conversions to external typesIf the destination type is not part of the current crate then you can'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 because we cannot implement a trait for a type if both the trait and the type are not defined by the current crate. This is due to Rust's orphaning rules. To bypass this, you can implement Into
directly:
struct Wrapper<T>(Vec<T>); impl<T> Into<Vec<T>> for Wrapper<T> { fn into(self) -> Vec<T> { self.0 } }
It is important to understand that Into
does not provide a From
implementation (as From
does with Into
). Therefore, you should always try to implement From
and then fall back to Into
if From
can't be implemented.
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.
String
implements Into<Vec<u8>>
:
In order to express that we want a generic function to take all arguments that can be converted to a specified type T
, we can use a trait bound of Into
<T>
. For example: The function is_hello
takes all arguments that can be converted into a Vec<u8>
.
fn is_hello<T: Into<Vec<u8>>>(s: T) { let bytes = b"hello".to_vec(); assert_eq!(bytes, s.into()); } let s = "hello".to_string(); is_hello(s);
fn into(self) -> T
Performs the conversion.
© 2010 The Rust Project Developers
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.
https://doc.rust-lang.org/std/convert/trait.Into.html