pub trait TryFrom<T>: Sized {
type Error;
// Required method
fn try_from(value: T) -> Result<Self, Self::Error>;
}
Expand description
Simple and safe type conversions that may fail in a controlled
way under some circumstances. It is the reciprocal of TryInto
.
This is useful when you are doing a type conversion that may
trivially succeed but may also need special handling.
For example, there is no way to convert an i64
into an i32
using the From
trait, because an i64
may contain a value
that an i32
cannot represent and so the conversion would lose data.
This might be handled by truncating the i64
to an i32
or by
simply returning i32::MAX
, or by some other method. The From
trait is intended for perfect conversions, so the TryFrom
trait
informs the programmer when a type conversion could go bad and lets
them decide how to handle it.
§Generic Implementations
TryFrom<T> for U
impliesTryInto
<U> for T
try_from
is reflexive, which means thatTryFrom<T> for T
is implemented and cannot fail – the associatedError
type for callingT::try_from()
on a value of typeT
isInfallible
. When the!
type is stabilizedInfallible
and!
will be equivalent.
TryFrom<T>
can be implemented as follows:
struct GreaterThanZero(i32);
impl TryFrom<i32> for GreaterThanZero {
type Error = &'static str;
fn try_from(value: i32) -> Result<Self, Self::Error> {
if value <= 0 {
Err("GreaterThanZero only accepts values greater than zero!")
} else {
Ok(GreaterThanZero(value))
}
}
}
§Examples
As described, i32
implements TryFrom<
i64
>
:
let big_number = 1_000_000_000_000i64;
// Silently truncates `big_number`, requires detecting
// and handling the truncation after the fact.
let smaller_number = big_number as i32;
assert_eq!(smaller_number, -727379968);
// Returns an error because `big_number` is too big to
// fit in an `i32`.
let try_smaller_number = i32::try_from(big_number);
assert!(try_smaller_number.is_err());
// Returns `Ok(3)`.
let try_successful_smaller_number = i32::try_from(3);
assert!(try_successful_smaller_number.is_ok());
Required Associated Types§
Required Methods§
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.
Implementors§
1.59.0 · source§impl TryFrom<char> for u8
impl TryFrom<char> for u8
Maps a char
with code point in U+0000..=U+00FF to a byte in 0x00..=0xFF with same value,
failing if the code point is greater than U+00FF.
See impl From<u8> for char
for details on the encoding.
type Error = TryFromCharError
1.74.0 · source§impl TryFrom<char> for u16
impl TryFrom<char> for u16
Maps a char
with code point in U+0000..=U+FFFF to a u16
in 0x0000..=0xFFFF with same value,
failing if the code point is greater than U+FFFF.
This corresponds to the UCS-2 encoding, as specified in ISO/IEC 10646:2003.
type Error = TryFromCharError
1.34.0 · source§impl<'a, T, const N: usize> TryFrom<&'a [T]> for &'a [T; N]
impl<'a, T, const N: usize> TryFrom<&'a [T]> for &'a [T; N]
Tries to create an array ref &[T; N]
from a slice ref &[T]
. Succeeds if
slice.len() == N
.
let bytes: [u8; 3] = [1, 0, 2];
let bytes_head: &[u8; 2] = <&[u8; 2]>::try_from(&bytes[0..2]).unwrap();
assert_eq!(1, u16::from_le_bytes(*bytes_head));
let bytes_tail: &[u8; 2] = bytes[1..3].try_into().unwrap();
assert_eq!(512, u16::from_le_bytes(*bytes_tail));
type Error = TryFromSliceError
1.34.0 · source§impl<'a, T, const N: usize> TryFrom<&'a mut [T]> for &'a mut [T; N]
impl<'a, T, const N: usize> TryFrom<&'a mut [T]> for &'a mut [T; N]
Tries to create a mutable array ref &mut [T; N]
from a mutable slice ref
&mut [T]
. Succeeds if slice.len() == N
.
let mut bytes: [u8; 3] = [1, 0, 2];
let bytes_head: &mut [u8; 2] = <&mut [u8; 2]>::try_from(&mut bytes[0..2]).unwrap();
assert_eq!(1, u16::from_le_bytes(*bytes_head));
let bytes_tail: &mut [u8; 2] = (&mut bytes[1..3]).try_into().unwrap();
assert_eq!(512, u16::from_le_bytes(*bytes_tail));
type Error = TryFromSliceError
1.43.0 · source§impl<T, A, const N: usize> TryFrom<Arc<[T], A>> for Arc<[T; N], A>where
A: Allocator,
impl<T, A, const N: usize> TryFrom<Arc<[T], A>> for Arc<[T; N], A>where
A: Allocator,
1.34.0 · source§impl<T, const N: usize> TryFrom<&[T]> for [T; N]where
T: Copy,
impl<T, const N: usize> TryFrom<&[T]> for [T; N]where
T: Copy,
Tries to create an array [T; N]
by copying from a slice &[T]
. Succeeds if
slice.len() == N
.
let bytes: [u8; 3] = [1, 0, 2];
let bytes_head: [u8; 2] = <[u8; 2]>::try_from(&bytes[0..2]).unwrap();
assert_eq!(1, u16::from_le_bytes(bytes_head));
let bytes_tail: [u8; 2] = bytes[1..3].try_into().unwrap();
assert_eq!(512, u16::from_le_bytes(bytes_tail));
type Error = TryFromSliceError
1.59.0 · source§impl<T, const N: usize> TryFrom<&mut [T]> for [T; N]where
T: Copy,
impl<T, const N: usize> TryFrom<&mut [T]> for [T; N]where
T: Copy,
Tries to create an array [T; N]
by copying from a mutable slice &mut [T]
.
Succeeds if slice.len() == N
.
let mut bytes: [u8; 3] = [1, 0, 2];
let bytes_head: [u8; 2] = <[u8; 2]>::try_from(&mut bytes[0..2]).unwrap();
assert_eq!(1, u16::from_le_bytes(bytes_head));
let bytes_tail: [u8; 2] = (&mut bytes[1..3]).try_into().unwrap();
assert_eq!(512, u16::from_le_bytes(bytes_tail));