Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

vector - How do I convert a Vec<String> to 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);
}

Are there better alternatives?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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

This uses coercion syntax.

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

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

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

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

and

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...