at54321
at54321

Reputation: 11708

Convert from Option<String> to non-empty &str w/o move

Is there a more efficient way to do this:

let s_opt = Some("Abc".to_string());
let s2 = &s_opt.clone().unwrap_or("".to_string());
println!("s_opt = {s_opt:?}, s2 = {s2:?}");

If I omit the clone() call, there will be a problem, because unwrap_or moves the wrapped String value.

Upvotes: 2

Views: 735

Answers (1)

at54321
at54321

Reputation: 11708

I think I found what I was looking for:

let s2 = s_opt.as_deref().unwrap_or("");

It's a bit shorter and avoids cloning the original String value.

Upvotes: 2

Related Questions