我如何转换 Vec<String>到 Vec&lt;&amp;str&gt;? [英] How do I convert a Vec&lt;String&gt; to Vec&lt;&amp;str&gt;?

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

问题描述

我可以通过这种方式将 Vec 转换为 Vec<&str>:

I can convert Vec<String> to Vec<&str> this way:

let mut items = Vec::<&str>::new();
for item in &another_items {
    items.push(item);
}

有更好的选择吗?

推荐答案

有很多方法可以做到,有些有缺点,有些只是对某些人来说更具可读性.

There are quite a few ways to do it, some have disadvantages, others simply are more readable to some people.

这将 s(属于 &String 类型)取消引用到 String右手边引用",然后取消引用通过 Deref trait 转换为 str 右手边引用",然后又变回 &str.这是在编译器中很常见的东西,因此我认为它是惯用的.

This dereferences s (which is of type &String) to a String "right hand side reference", which is then dereferenced through the Deref trait to a str "right hand side reference" and then turned back into a &str. This is something that is very commonly seen in the compiler, and I therefor consider it idiomatic.

let v2: Vec<&str> = v.iter().map(|s| &**s).collect();

这里将 Deref trait 的 deref 函数传递给 map 函数.它非常简洁,但需要use使用特征或提供完整路径.

Here the deref function of the Deref trait is passed to the map function. It's pretty neat but requires useing the trait or giving the full path.

let v3: Vec<&str> = v.iter().map(std::ops::Deref::deref).collect();

这使用强制语法.

let v4: Vec<&str> = v.iter().map(|s| s as &str).collect();

这需要 String 的一个 RangeFull 切片(只是整个 String 中的一个切片)并引用它.在我看来这很丑陋.

This takes a RangeFull slice of the String (just a slice into the entire String) and takes a reference to it. It's ugly in my opinion.

let v5: Vec<&str> = v.iter().map(|s| &s[..]).collect();

这是使用强制转换将 &String 转换为 &str.将来也可以替换为 s: &str 表达式.

This is uses coercions to convert a &String into a &str. Can also be replaced by a s: &str expression in the future.

let v6: Vec<&str> = v.iter().map(|s| { let s: &str = s; s }).collect();

以下(感谢@huon-dbaupp)使用了 AsRef 特性,该特性仅用于从拥有的类型映射到它们各自的借用类型.有两种使用方法,同样,任何一个版本的漂亮程度都是完全主观的.

The following (thanks @huon-dbaupp) uses the AsRef trait, which solely exists to map from owned types to their respective borrowed type. There's two ways to use it, and again, prettiness of either version is entirely subjective.

let v7: Vec<&str> = v.iter().map(|s| s.as_ref()).collect();

let v8: Vec<&str> = v.iter().map(AsRef::as_ref).collect();

<小时>

我的底线是使用 v8 解决方案,因为它最明确地表达了您的需求.


My bottom line is use the v8 solution since it most explicitly expresses what you want.

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

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