In Rust programs, we often need to convert between types with the from()
and into()
functions. To enable these functions for custom structs, we can implement the "From" trait.
With the impl
keyword, we can provide an implementation for the From trait. In the from function, we receive the source type, and return Self.
This program contains 2 custom structs, Range and RangeCompressed
. In Range, we have 2 usize
fields, and in RangeCompressed
, these fields have been changed to u16
fields.
impl
From that specifies Range and RangeCompressed
as its source and target types.from()
function within the From impl
block receives a Range, and returns a RangeCompressed
(with its fields cast).into()
to get a RangeCompressed
. We verify with println
that the start and end fields are correct.into()
and from()
functions. Here we call from()
on the RangeCompressed
type.struct Range { start: usize, end: usize, } struct RangeCompressed { start: u16, end: u16, } impl From<Range> for RangeCompressed { fn from(range: Range) -> Self { // For from, just cast the internal fields of the struct. RangeCompressed { start: range.start as u16, end: range.end as u16, } } } fn main() { // Version 1: use into to convert one struct to another with From trait. let range = Range { start: 0, end: 10 }; let range_compressed: RangeCompressed = range.into(); println!( "start: {} end: {}", range_compressed.start, range_compressed.end ); // Version 2: use from method for conversion. let range2 = Range { start: 50, end: 100, }; let range_compressed2 = RangeCompressed::from(range2); println!( "start: {} end: {}", range_compressed2.start, range_compressed2.end ); }start: 0 end: 10 start: 50 end: 100
Rust programs typically contain a significant amount of code that casts and converts types. This is required as the language is strict with type-checking.
byte
size of a struct
, the From trait can be useful and elegant.The From trait is not necessary in Rust code, but having it present can simplify how programs are written. It can make programs more elegant. And this is often worth the effort involved.