TIL: Rust - Some(T) or T
Today i was asking myself a question with Optional in Rust, about the necessity to write some boilerplate code like this:
pub fn my_function(optional_input: Option<MyStruct>) {
...
}
...
let input = MyStruct::new();
my_function(input); // Doesn't compile
my_function(Some(input)); // Compile
my_function(None); // CompileOkay even if it's little, that seems like unnecessary boilerplate to write the Some(x) part ?, like i know that there is "some" value here, so i started wondering:
Is there any way to write a function that take Option<T> or T and convert the T to Some(T) ?
Well, surprisingly enough i didn't find much about this on the internet, until i came across an old post on Reddit this article (the website wasn't even working, i had to go into the WebArchive to find more about)
And that's where i found the solution, something very simple.
A default implementation of Rust for From<T> for Option<T>
impl<T> From<T> for Option<T> {
fn from(val: T) -> Option<T> {
Some(val)
}
}
The solution was indeed very simple:
pub fn my_function(optional_input: impl Into<Option<MyStruct>>) {
let optional_input = optional_input.into();
...
}
let input = MyStruct::new();
my_function(input); // Compile
my_function(Some(input)); // Compile
my_function(None); // Compile
Member discussion