Rust Reference ยท Core Traits
The From and Into traits
Reference for the Rust From and Into traits: implement From to get Into, convert numbers and strings, use From with the ? operator and avoid common pitfalls.
From<T> converts a T into Self and cannot fail. Into<U> is the same conversion seen from the other side: x.into(). You implement From, and the standard library gives you Into automatically through a blanket impl, so you rarely write Into by hand.
Use them for natural, lossless conversions: String::from("hi"), f64::from(3_i32), wrapping an error in your own error enum, or building a struct from a tuple. For conversions that can fail, see TryFrom and TryInto.
let s: String = "hello".into(); let n = i64::from(7_i32);
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
pub trait From<T>: Sized { fn from(value: T) -> Self; } pub trait Into<T>: Sized { fn into(self) -> T; }
| Name | Description |
|---|---|
value / self |
The input, taken by value (it is consumed or copied). |
T |
The source type for From<T>; the target type for Into<T>. |
Returns: the converted value. Neither method may fail or panic by contract. Use TryFrom if conversion can be rejected.
Usage notes
- Implement
From, notInto.impl From<A> for Bautomatically providesimpl Into<B> for A. ImplementingIntodirectly is only needed when the orphan rule blocksFrom. - Accept
impl Into<String>in constructors so callers can pass&strorStringwithout ceremony:fn new(name: impl Into<String>). For read-only access use&strorAsRef<str>instead, seeAsRefandAsMut. - The
?operator callsFrom::fromon the error. ImplementingFrom<IoError> for MyErroris what lets?convert errors for you. See question mark. - Reflexive: every type implements
From<Self>, which is whydescribe(Point {..})compiled above. - Lossless numeric widening only:
i64::from(i32)exists,i32::from(i64)does not. Narrowing usesTryFromor theascast. - Inference:
.into()needs a known target type.let x = y.into();with nothing else constrainingxfails to compile with "type annotations needed". - Conversions cost what they cost:
String::from("x")allocates;From<String> for Box<str>may reallocate.Fromdoes not promise it is cheap, only that it cannot fail. - Collections:
Vec::from([1, 2, 3]),HashMap::from([(k, v), ...]),BTreeSet::from(array)andString::from(char)are common one-liners.