Reputation: 8533
How do I write a function like this:
pub fn unwrap_some_or_none_with_error(input: Option<&'static str>) -> &str {
input.unwrap_or(0)
}
So that when None is sent to this function it will return 0
, and when an Option like Some
is sent it unwraps it ?
Upvotes: 0
Views: 407
Reputation: 23434
That's not possible: Rust is a typed language so everything can only have a single type. The idiomatic way to do what you describe is to use a Result
, which can hold either a value or an error. This Result
can be created with ok_or
:
pub fn unwrap_some_or_none_with_error(input: Option<&'static str>) -> Result<&str, i32> {
input.ok_or(0)
}
Upvotes: 1