A Rust question!
Converting an Option<T1> to an Option<T2> is a common pattern, and Rust provides a beautiful, idiomatic way to do it: map()!
Here's the magic:
let opt_t1: Option<T1> = /* some value */;
let opt_t2: Option<T2> = opt_t1.map(|t1| /* convert T1 to T2 here */);
The map() method applies a transformation function (the closure |t1| ...) to the inner value T1 if it exists (i.e., if opt_t1 is Some(T1)). If opt_t1 is None, map() simply returns None, without executing the closure.
In other words:
Some(T1) → Some(T2) (apply the conversion)
None → None (no conversion needed, just propagate the absence of value)
Example time!
struct Person {
name: String,
}
struct PersonDto {
name: String,
}
fn main() {
let maybe_person: Option<Person> = Some(Person {
name: "John".to_string(),
});
// Convert Option<Person> to Option<PersonDto>
let maybe_dto: Option<PersonDto> = maybe_person.map(|p| PersonDto { name: p.name });
assert_eq!(
maybe_dto,
Some(PersonDto {
name: "John".to_string()
})
);
// Test with None
let no_person: Option<Person> = None;
let no_dto: Option<PersonDto> = no_person.map(|p| PersonDto { name: p.name });
assert_eq!(no_dto, None);
}
In this example, we convert Person to PersonDto using map(). If maybe_person is Some, we create a new PersonDto instance with the same name. If it's None, maybe_dto will also be None.
Why is this better than other approaches?
- Concise: One method call, no boilerplate.
- Expressive: Clearly conveys the intent: "transform the inner value, if present".
- Efficient: No unnecessary clones or moves; the closure only executes when there's a value to transform.
- Idiomatic: This is how Rustaceans do it; your code will be instantly readable to fellow Rust developers.
Other alternatives, like if let or match, would work too, but they're more verbose:
// if let (verbose)
let opt_t2 = if let Some(t1) = opt_t1 {
Some(/* convert T1 to T2 */)
} else {
None
};
// match (even more verbose)
let opt_t2 = match opt_t1 {
Some(t1) => Some(/* convert T1 to T2 */),
None => None,
};
So, remember: when converting Option<T1> to Option<T2>, map() is your friend!
Happy Rusting!