As of Rust 1.40, the standard library has Option::as_deref
to do this:
fn main() {
let opt: Option<String> = Some("some value".to_owned());
let value = opt.as_deref().unwrap_or("default string");
}
See also:
More Related Contents:
- Why can’t I store a value and a reference to that value in the same struct?
- The compiler suggests I add a ‘static lifetime because the parameter type may not live long enough, but I don’t think that’s what I want
- How do I stop iteration and return an error when Iterator::map returns a Result::Err?
- Are polymorphic variables allowed?
- Why does Iterator::take_while take ownership of the iterator?
- When should I implement std::convert::From vs std::convert::Into?
- Sending trait objects between threads in Rust
- Why would I implement methods on a trait instead of as part of the trait?
- How to initialize struct fields which reference each other
- “Expected fn item, found a different fn item” when working with function pointers
- How do you unwrap a Result on Ok or return from the function on Err?
- How do I read the entire body of a Tokio-based Hyper request?
- How can I downcast from Box to a trait object type?
- When returning the outcome of consuming a StdinLock, why was the borrow to stdin retained?
- How does Rust pattern matching determine if the bound variable will be a reference or a value?
- What is a crate attribute and where do I add it?
- Parameter type may not live long enough?
- Why does Rust disallow mutable aliasing?
- How to store rusqlite Connection and Statement objects in the same struct in Rust? [duplicate]
- How to model complex recursive data structures (graphs)?
- print! macro not executed until pressing Enter
- How can I define an async method in a trait?
- How do I specify the linker path in Rust?
- Why am I getting “parameter is never used [E0392]”?
- How do I specify that a struct field must implement a trait?
- What does Rust’s unary || (parallel pipe) mean?
- How to create and write to memory mapped files?
- Downcast traits inside Rc for AST manipulation
- How to check in Rust if architecture is 32 or 64 bit?
- Is there any way to restrict a generic type to one of several types?