HiveBrain v1.2.0
Get Started
← Back to all entries
patternrustCritical

Converting from Option<String> to Option<&str>

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
fromconvertingstroptionstring

Problem

Very often I have obtained an Option from a calculation, and I would like to either use this value or a default hardcoded value.

This would be trivial with an integer:

let opt: Option = Some(3);
let value = opt.unwrap_or(0); // 0 being the default


But with a String and a &str, the compiler complains about mismatched types:

let opt: Option = Some("some value".to_owned());
let value = opt.unwrap_or("default string");


The exact error here is:
error[E0308]: mismatched types
--> src/main.rs:4:31
|
4 | let value = opt.unwrap_or("default string");
| ^^^^^^^^^^^^^^^^
| |
| expected struct
std::string::String, found reference
| help: try using a conversion method:
"default string".to_string()
|
= note: expected type
std::string::String
found type
&'static str


One option is to convert the string slice into an owned String, as suggested by rustc:

let value = opt.unwrap_or("default string".to_string());


But this causes an allocation, which is undesirable when I want to immediately convert the result back to a string slice, as in this call to Regex::new():

let rx: Regex = Regex::new(&opt.unwrap_or("default string".to_string()));


I would rather convert the Option to an Option to avoid this allocation.

What is the idiomatic way to write this?

Solution

As of Rust 1.40, the standard library has Option::as_deref to do this:

fn main() {
    let opt: Option = Some("some value".to_owned());
    let value = opt.as_deref().unwrap_or("default string");
}


See also:

  • How can I iterate on an Option>?

Code Snippets

fn main() {
    let opt: Option<String> = Some("some value".to_owned());
    let value = opt.as_deref().unwrap_or("default string");
}

Context

Stack Overflow Q#31233938, score: 194

Revisions (0)

No revisions yet.