根据 Steve Klabnik's writeup in the pre-Rust 1.0 documentation on the difference between String
and &str
, 在 Rust 中你应该使用 &str
除非你真的需要拥有 String
的所有权.同样,建议使用对切片的引用 ( &[]
) 而不是 Vec
除非您真的需要 Vec
的所有权.
我有一个 Vec<String>
我想写一个使用这个字符串序列的函数,它不需要对 Vec
的所有权或 String
实例,该函数是否应该采用 &[&str]
?如果是这样,引用 Vec<String>
的最佳方式是什么?进入&[&str]
?或者,这种强制是否矫枉过正?
最佳答案
您可以使用 AsRef
trait 创建一个接受 &[String]
和 &[&str]
的函数:
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);
}
关于string - 在 Rust 中将 Vec<String> 转换为 &str 的一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41179659/