Rust Reference ยท Standard Library Modules
The std::convert module
Reference for Rust std::convert: From, Into, TryFrom, TryInto, AsRef, AsMut, Infallible and identity, with when to use each conversion trait.
std::convert defines the traits Rust uses for converting between types. They split along two axes: whether the conversion can fail, and whether it consumes the value or just borrows a view of it.
From<T> and Into<T> are infallible and consuming. TryFrom<T> and TryInto<T> are the same but return a Result. AsRef<T> and AsMut<T> are cheap reference-to-reference conversions that do not consume anything. All six traits are in the prelude (the Try* pair since edition 2021); Infallible and identity need an explicit path.
let n: i64 = i64::from(7_i32); let small: Result<u8, _> = u8::try_from(300_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
trait From<T>: Sized { fn from(value: T) -> Self; } trait Into<T>: Sized { fn into(self) -> T; } trait TryFrom<T>: Sized { type Error; fn try_from(value: T) -> Result<Self, Self::Error>; } trait TryInto<T>: Sized { type Error; fn try_into(self) -> Result<T, Self::Error>; } trait AsRef<T: ?Sized> { fn as_ref(&self) -> &T; } trait AsMut<T: ?Sized> { fn as_mut(&mut self) -> &mut T; } enum Infallible {} fn identity<T>(x: T) -> T
| Item | Description |
|---|---|
From / Into |
Implement From; Into is provided by a blanket impl. Used by ? to convert error types. |
TryFrom / TryInto |
Fallible versions. Integer narrowing returns TryFromIntError. |
AsRef / AsMut |
Cheap borrow conversions; common in generic function parameters (AsRef<Path>, AsRef<str>). |
Infallible |
An uninhabited enum, the error type of conversions that cannot fail. |
identity |
Returns its argument. |
Usage notes
- Implement
From, notInto. The blanketimpl<T, U: From<T>> Into<U> for Tgives youInto. ImplementIntodirectly only whenFromwould violate the orphan rule. Frommust not fail or lose data; useTryFromwhen it can. ReflexiveFrom<T> for Talways exists.TryFromis automatic for everyFromimpl (withError = Infallible), so generic code overTryFromaccepts infallible conversions too.?callsFrom:Err(e)?convertseinto the function's error type, which is howBox<dyn Error>and custom error enums collect many error sources.AsRefvsBorrow:AsRefcarries no promises about equality and hashing;Borrowdoes, andHashMap::getusesBorrow.- Casting with
asis separate: it never fails, truncates silently and is not part of these traits. - Prefer
impl AsRef<str>orimpl Into<String>in public APIs to accept both&strandStringwithout forcing callers to convert. let Ok(v) = ...with anInfallibleerror compiles without anelsebranch because theErrcase cannot occur.