string - 在 Rust 中将 Vec<String> 转换为 &str 的一部分?

标签 string vector reference rust ownership

根据 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/53071517/

相关文章:

ruby - 当字符串包含数字时,为什么 Ruby 的 String#to_i 有时会返回 0?

c++ - 如何随机输出两个字符串之一?

java - 在 Coldfusion/Java 中拆分多语言字符串

c++ - std::vector.pop_back() 会改变 vector 的容量吗?

c++ - 将 Ref 返回给局部变量

java - 何时清理ReferenceQueue?被系统清理了?

c - 程序 "double reading"一个字符串

C++:如何为多维 vector 创建构造函数?

vector 的 C++ 初始化

c++ - "overloaded member function not found"引用