In this lesson, you will learn how to create ergonomic, idiomatic conversion pipelines between your custom types using the From and Into traits.
The Power of Type Conversions
In Rust, you often need to transform one type into another—for instance, converting a raw input string into a structured User domain model. While you could write custom methods like to_user(), the From and Into traits provide a standardized way to signal that a conversion is effortless and infallible.
Defining From and Into
The From trait is the primary one you implement. It requires a single method: from(value: T). When you implement From<T> for your type U, Rust automatically provides an implementation of Into<U> for your type T for free.
This "free" implementation is why we prefer Into when writing generic functions.
struct Celsius(f64);
struct Fahrenheit(f64);
impl From<Celsius> for Fahrenheit {
fn from(c: Celsius) -> Self {
Fahrenheit(c.0 * 1.8 + 32.0)
}
}
fn print_temp<T: Into<Fahrenheit>>(temp: T) {
let f: Fahrenheit = temp.into();
println!("Temperature in F: {}", f.0);
}
fn main() {
let hot = Celsius(30.0);
// We can pass Celsius because it implements Into<Fahrenheit>
print_temp(hot);
}
Why use this instead of a custom method?
- Ergonomics: By accepting
T: Into<U>as a generic bound, you allow your functions to accept either the original type or the converted type seamlessly. - Consistency: Other developers working on your project will immediately recognize the
from()andinto()pattern. It tells them: "This conversion is intended to be used, it won't crash (panic), and it’s the standard way to change this data’s shape." - Pipeline capability: You can chain conversions naturally when you have multiple steps in your domain logic, keeping your code clean and expressive.
Remember: Implement From to define the conversion logic, and use Into to keep your function signatures flexible and clean.
Key Takeaway: Always implement From to enable the Into trait, allowing your types to be converted flexibly and idiomatically throughout your application.