3 ms·
You can use From and TryFrom, like u32::try_from(5i32). https://doc.rust-lang.org/std/convert/trait.From.html https://doc.rust-lang.org/std/convert/trait.From.h
by nayuki 4y ago
You can use From and TryFrom, like u32::try_from(5i32). https://doc.rust-lang.org/std/convert/trait.From.html https://doc.rust-lang.org/std/convert/trait.From.html , https://doc.rust-lang.org/std/convert/trait.TryFrom.html https://doc.rust-lang.org/std/convert/trait.TryFrom.html
- tialaramex 4y agoAnd, notably in this context, Rust's traits are auto-implemented in a chain, so if From<Foo> for Bar, then Into<Bar> for Foo, and thus TryFrom<Foo> for Bar, and thus in turn TryInto<Bar> for Foo. This means that if first_thing used to have a non-overlapping value space so that converting it to other_thing might fail, so you wrote other_thing = first_thing.try_into().blahblahblah; ... if you later refactor and now first_thing is a subset of other_thing so that the conversion can never fail, the previous code still works fine, the try_into() call just never fails. In fact, the compiler even knows it can't fail, because its error type is now Infallible, a sum type with nothing in it, so the compiler can see this never happens, and optimise accordingly.