From::from, Into::into, TryFrom::try_from, TryInto::try_into
pub trait From<T>: Sized {
fn from(value: T) -> Self;
}
pub trait Into<T>: Sized {
fn into(self) -> T;
}
pub trait TryFrom<T>: Sized {
type Error;
fn try_from(value: T) -> Result<Self, Self::Error>;
}
pub trait TryInto<T>: Sized {
type Error;
fn try_into(self) -> Result<T, Self::Error>;
}Convert a value infallibly with From or Into, or fallibly with TryFrom or TryInto.
| Parameter | Description |
|---|---|
value / self | The value being converted. From and TryFrom are written on the target type; Into and TryInto are methods on the source value. |
Returns: From and Into return the target type. TryFrom and TryInto return Result, with an associated Error type such as std::num::TryFromIntError for integer range checks.
Errors and panics
TryFromIntError— Returned when an integer cannot be represented in the target type. The Display text above was checked on rustc 1.90.0 and is a standard-library message, not an OS string.
- There is a blanket From<T> for T, the identity conversion. Avoid writing a conflicting reflexive From impl.
- PathBuf implements From<String> and From<&str>, which is a way to go from an owned string to an owned path.
use std::convert::TryInto;
use std::path::PathBuf;
fn main() {
let n: u32 = u32::from(7u16);
let n2: u32 = 7u16.into();
println!("from-into {n} {n2}");
match u16::try_from(80u32) {
Ok(v) => println!("try_from ok {v}"),
Err(e) => println!("try_from err {e}"),
}
match u16::try_from(70_000u32) {
Ok(v) => println!("try_from ok {v}"),
Err(e) => println!("try_from err {e}"),
}
let via_into: Result<u16, _> = 80u32.try_into();
println!("try_into {via_into:?}");
let buf = PathBuf::from(String::from("tmp/foo"));
println!("pathbuf-from {}", buf.display());
}Expected output
from-into 7 7
try_from ok 80
try_from err out of range integral type conversion attempted
try_into Ok(80)
pathbuf-from tmp/fooRelated: Option and Result page, Path and PathBuf