转换 Vec<String>进入 Rust 中的 &amp;str 片段? [英] Convert Vec&lt;String&gt; into a slice of &amp;str in Rust?

查看:65
本文介绍了转换 Vec<String>进入 Rust 中的 &amp;str 片段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 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 Vecs 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 中的 &amp;str 片段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆