TryFrom and TryInto
Initially added:
The TryFrom
and
TryInto
traits are like the
From
and
Into
traits, except that they return a
result, meaning that they may fail.
For example, the from_be_bytes
and related methods on integer types take
arrays, but data is often read in via slices. Converting between slices and
arrays is tedious to do manually. With the new traits, it can be done inline
with .try_into()
:
use std::convert::TryInto; fn main() -> Result<(), Box<dyn std::error::Error>> { let slice = &[1, 2, 3, 4][..]; let num = u32::from_be_bytes(slice.try_into()?); Ok(()) }