我在编写一个将字符串集合作为参数的函数时遇到了麻烦.我的功能看起来像这样:
type StrList<'a> = Vec<&'a str>;
fn my_func(list: &StrList) {
for s in list {
println!("{}", s);
}
}
Run Code Online (Sandbox Code Playgroud)
如果我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>`
Run Code Online (Sandbox Code Playgroud)
这是主要使用的:
fn main() {
let v1 = vec!["a", "b"];
let v2 = vec!["a".to_owned(), "b".to_owned()];
my_func(&v1);
my_func(&v2);
}
Run Code Online (Sandbox Code Playgroud)
我的函数无法获取自有字符串的向量.相反,如果我将StrList类型更改为:
type StrList = Vec<String>;
Run Code Online (Sandbox Code Playgroud)
第一次调用失败,第二次调用失败.
一种可能的解决方案是以这种方式生成一个Vec<&'a str> …
我想拆分一个字符串并Vec<String>从我的函数返回.它必须是,Vec<String>而不是Vec<&str>因为我不能回来Vec<&str>,可以吗?但是,如果可以的话,我该怎么做?
let var1: Vec<&str> = my_string.split("something").collect();
let res = var1.iter().map(|x| x.to_string());
// I want to return Vec<String>
Run Code Online (Sandbox Code Playgroud)
我尝试了不同的版本,但得到了error: mismatched types其他类似的错误.有没有更简单的方法?
我曾经广泛使用Vec<&str>,但 Discord 上有人建议我将其更改为&[&str],但在某些情况下这会产生问题。以这段曾经有效的代码为例,
fn main() {
let pos: Vec<String> = vec!["foo".to_owned(), "bar".to_owned(), "baz".to_owned()];
let pos: Vec<&str> = pos.iter().map(AsRef::as_ref).collect();
}
Run Code Online (Sandbox Code Playgroud)
当我将第二行更改为
let pos: &[&str] = pos.iter().map(AsRef::as_ref).collect();
Run Code Online (Sandbox Code Playgroud)
我收到错误,
error[E0277]: a value of type `&[&str]` cannot be built from an iterator over elements of type `&_`
--> bin/seq.rs:3:51
|
3 | let pos: &[&str] = pos.iter().map(AsRef::as_ref).collect();
| ^^^^^^^ value of type `&[&str]` cannot be built from `std::iter::Iterator<Item=&_>`
|
= help: the trait `FromIterator<&_>` is not implemented for `&[&str]`
Run Code Online (Sandbox Code Playgroud)
我怎样才能将 …