Is there a more concise way to achieve the following?
fn boxed_option<T>(thing: Option<T>) -> Option<Box<T>> {
match thing {
Some(x) => Some(Box::new(x)),
None => None,
}
}
Is there a more concise way to achieve the following?
fn boxed_option<T>(thing: Option<T>) -> Option<Box<T>> {
match thing {
Some(x) => Some(Box::new(x)),
None => None,
}
}
Yes:
thing.map(Box::new)
I would strongly recommend memorizing all the methods on Iterator
, Option
and Result
as they are so pervasively used in Rust. Option
and Result
have fewer than 25 inherent methods each, many of which have substantial overlap between the two types. At least read all of them to know what is available and memorize that. You can always open up the documentation again to find the exact name.
I actually can't quite get this to work.
fn function_2<F>(foo: Option<F>) where F: 'static + FnMut() { let tmp: Option<Box<FnMut()>> = foo.map(Box::new); }
error[E0308]: mismatched types --> src/main.rs:14:37 | 14 | let tmp: Option<Box<FnMut()>> = foo.map(Box::new); | ^^^^^^^^^^^^^^^^^ expected trait std::ops::FnMut, found type parameter | = note: expected type `std::option::Option<Box<std::ops::FnMut()>>` = note: found type `std::option::Option<Box<F>>`
The original code here wan't just transforming one type to another, it was also creating a trait object. I can't say for sure why that form of creating a trait object allowed to be implicit and this isn't:
foo.map(|f| Box::new(f));
However, you can instead say:
foo.map(|f| Box::new(f) as Box<FnMut()>);
(and no need to specify the type on the variable, of course).
Pedantically, "boxing an Option
" would be Box<Option<T>>
.