相关疑难解决方法(0)

如何编写一个既拥有和不拥有字符串集合的函数?

我在编写一个将字符串集合作为参数的函数时遇到了麻烦.我的功能看起来像这样:

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> …

string rust

9
推荐指数
2
解决办法
443
查看次数

拆分一个字符串并返回Vec <String>

我想拆分一个字符串并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其他类似的错误.有没有更简单的方法?

rust

8
推荐指数
2
解决办法
3730
查看次数

如何将 Vec&lt;String&gt; 转换为 &amp;[&amp;str]?

我曾经广泛使用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)

我怎样才能将 …

string vector type-conversion rust

3
推荐指数
1
解决办法
1673
查看次数

标签 统计

rust ×3

string ×2

type-conversion ×1

vector ×1