如何转换 Vec<String>到 Vec<&str>? [英] How do I convert a Vec<String> to Vec<&str>?
问题描述
我可以通过这种方式将 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
特征的 deref
函数被传递给 map
函数.它非常简洁,但需要使用
特征或给出完整路径.
Here the deref
function of the Deref
trait is passed to the map
function. It's pretty neat but requires use
ing 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<&str>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!