【发布时间】:2015-09-22 18:02:51
【问题描述】:
我在编写一个将字符串集合作为参数的函数时遇到问题。我的函数如下所示:
type StrList<'a> = Vec<&'a str>;
fn my_func(list: &StrList) {
for s in list {
println!("{}", s);
}
}
如果我按预期将Vec<&'a str> 传递给函数,一切都会顺利进行。但是,如果我通过 Vec<String> 编译器会抱怨:
error[E0308]: mismatched types
--> src/main.rs:13:13
|
13 | my_func(&v2);
| ^^^ expected &str, found struct `std::string::String`
|
= note: expected type `&std::vec::Vec<&str>`
= note: found type `&std::vec::Vec<std::string::String>`
这是主要使用的:
fn main() {
let v1 = vec!["a", "b"];
let v2 = vec!["a".to_owned(), "b".to_owned()];
my_func(&v1);
my_func(&v2);
}
我的函数无法获取拥有字符串的向量。相反,如果我将StrList 类型更改为:
type StrList = Vec<String>;
第一次调用失败,第二次成功。
一种可能的解决方案是以这种方式从v2 生成Vec<&'a str>:
let v2_1 : Vec<_> = v2.iter().map(|s| s.as_ref()).collect();
但这对我来说似乎很奇怪。 my_func 不应该关心字符串的所有权。
my_func 应该使用哪种签名来支持拥有的字符串向量和字符串引用?
【问题讨论】: