Rust通过空格分割线:没有为type&str找到方法collect

问题描述 投票:0回答:1

我试图逐行处理命令的输出,我坚持处理str::Lines。我试图获取每一行所有单词并处理它们(与某些模式比较)

我的代码:

// output came properly from command
let mut lines = String::from_utf8_lossy(&output.stdout).to_string().lines();

for line in lines {
    let vec: Vec<&str> = line.collect();

    // Try to do something with a split...  

编译抱怨:

error[E0599]: no method named `collect` found for type `&str` in the current scope
   --> src/main.rs:218:39
    |
218 |             let vec: Vec<&str> = line.collect();
    |                                       ^^^^^^^
    |
    = note: the method `collect` exists but the following trait bounds were not satisfied:
            `&mut &str : std::iter::Iterator`
            `&mut str : std::iter::Iterator`

我想我可以将行复制为字符串并尝试转换它但是,因为我是Rust的新手想要一些建议/帮助我如何更顺利地转换线?

rust
1个回答
0
投票

好的,我想出了如何解决这个问题,示例中出现了一些错误:

  1. 由于生命周期,我需要字符串而不是行
  2. 可变性在这里不是问题,所以只是删除
  3. 迭代和str我需要提取Iterator? (不确定在这里,仍然觉得Rust docs有点不舒服...)
let s = String::from_utf8_lossy(&output.stdout).to_string();

for line in s.lines() {
    let vec: Vec<&str> = line.split(' ').collect();

    // Try to do something with a split... 
© www.soinside.com 2019 - 2024. All rights reserved.