转换 Vec<String>进入 Rust 中的 &str 片段? [英] Convert Vec<String> into a slice of &str in Rust?
问题描述
根据 Steve Klabnik 在关于 String
和 &str
之间区别的 pre-Rust 1.0 文档,在 Rust 中你应该使用 &str
除非您确实需要对 String
拥有所有权.同样,除非您确实需要对 Vec
的所有权,否则建议使用对切片 (&[]
) 的引用而不是 Vec
.
Per Steve Klabnik's writeup in the pre-Rust 1.0 documentation on the difference between String
and &str
, in Rust you should use &str
unless you really need to have ownership over a String
. Similarly, it's recommended to use references to slices (&[]
) instead of Vec
s unless you really need ownership over the Vec
.
我有一个 Vec
并且我想编写一个使用这个字符串序列的函数,它不需要对 Vec
或 的所有权>String
实例,该函数应该采用 &[&str]
吗?如果是这样,将 Vec
引用到 &[&str]
的最佳方法是什么?或者,这种强制是不是太过分了?
I have a Vec<String>
and I want to write a function that uses this sequence of strings and it doesn't need ownership over the Vec
or String
instances, should that function take &[&str]
? If so, what's the best way to reference the Vec<String>
into &[&str]
? Or, is this coercion overkill?
推荐答案
您可以创建一个接受 &[String]
和 &[&str]
的函数code> 使用 AsRef
trait:
You can create a function that accepts both &[String]
and &[&str]
using the AsRef
trait:
fn test<T: AsRef<str>>(inp: &[T]) {
for x in inp { print!("{} ", x.as_ref()) }
println!("");
}
fn main() {
let vref = vec!["Hello", "world!"];
let vown = vec!["May the Force".to_owned(), "be with you.".to_owned()];
test(&vref);
test(&vown);
}
这篇关于转换 Vec<String>进入 Rust 中的 &str 片段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!