如何转换 Option&lt;&amp;T&gt;到 Option<T>以 Rust 中最惯用的方式? [英] How to convert Option&lt;&amp;T&gt; to Option&lt;T&gt; in the most idiomatic way in Rust?

查看:50
本文介绍了如何转换 Option&lt;&amp;T&gt;到 Option<T>以 Rust 中最惯用的方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用HashMap的get方法时,得到一个Option<&T>,这次又遇到了Option<&String>;.我想获得一个拥有的值 Option.如果我不写 map(|x| x.to_owned()),这可能吗?

When using HashMap's get method, I get an Option<&T>, I've encountered it again this time with Option<&String>. I'd like to get an owned value Option<String>. Is this possible without me writing map(|x| x.to_owned())?

我只是想知道是否有办法为任何实用程序特性编写一个全面的实现来实现这一目标?

I'm just wondering if there's a way to write a blanket implementation for any of the utility traits to achieve that?

推荐答案

Option 带有用于各种转换的实用方法,这些方法在 其文档.对于任何实现 Clone(String 实现)的 TOption<&T>::cloned 可以满足您的需求.

Option comes with utility methods for various transformations, which are listed in its documentation. For any T that implements Clone (which String does), Option<&T>::cloned does what you're looking for.

CloneToOwned 更具体,所以 .cloned() 不是 exact 匹配.map(|x| x.to_owned()).例如,它不会将 Option<&str> 变成 Option;为此,您必须坚持使用 map.

Clone is more specific than ToOwned, so .cloned() isn't an exact match for .map(|x| x.to_owned()). For example, it won't turn an Option<&str> into an Option<String>; for that you will have to stick with map.

从 Rust 1.35 开始,当 TCopy 时,.copied().cloned() 做同样的事情,但它会失败当 T 不是 Copy 时编译.当您想明确表示克隆很便宜时,您可以使用它.

Since Rust 1.35, when T is Copy, .copied() does the same thing as .cloned(), but it will fail to compile when T is not Copy. You might use this when you want to be explicit that the clone is cheap.

另见:

这篇关于如何转换 Option&lt;&amp;T&gt;到 Option<T>以 Rust 中最惯用的方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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