从 Option<String> 转换到选项&lt;&amp;str&gt; [英] Converting from Option&lt;String&gt; to Option&lt;&amp;str&gt;

查看:38
本文介绍了从 Option<String> 转换到选项&lt;&amp;str&gt;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常从计算中获得一个 Option,我想使用这个值或默认的硬编码值.

Very often I have obtained an Option<String> 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<i32> = Some(3);
let value = opt.unwrap_or(0); // 0 being the default

但是对于 String&str,编译器会抱怨类型不匹配:

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

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

这里的确切错误是:

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`

一种选择是将字符串切片转换为拥有的字符串,如 rustc 所建议的:

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());

但这会导致分配,当我想立即将结果转换回字符串切片时,这是不可取的,就像对 Regex::new() 的调用一样:

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()));

我宁愿将 Option 转换为 Option<&str> 以避免这种分配.

I would rather convert the Option<String> to an Option<&str> to avoid this allocation.

写这个的惯用方式是什么?

What is the idomatic way to write this?

推荐答案

从 Rust 1.40 开始,标准库有 Option::as_deref 这样做:

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");
}

另见:

这篇关于从 Option<String> 转换到选项&lt;&amp;str&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆