From and Into for type conversions

9674
0

The From and Into traits provide a standard way to convert between types. Implementing From<T> for your type automatically provides Into<T> via a blanket implementation. I use From for infallible conversions (like String::from("hello")) and TryFrom for fallible ones. This is more idiomatic than custom to_* methods. The ? operator works with From for error conversion: if your error type implements From<OtherError>, you can use ? on functions returning OtherError. I implement From for wrapping types (newtype pattern) and converting between representations. The trait makes APIs composable and consistent with standard library types.