gpt4 book ai didi

rust - 在String.split之后使用链使用rust

转载 作者:行者123 更新时间:2023-12-03 11:28:29 25 4
gpt4 key购买 nike

我有一段有效的代码:

for line in content
.split('\n')
.collect::<Vec<_>>()
.iter()
.chain((&["output"]).iter())

我认为必须有一种方法可以使用split提供的迭代器来获得相同的结果,而不必将collect()放入向量中。
当我尝试将 .collect::<Vec<_>>().iter()更改为 into_iter()时,出现以下错误:
error[E0271]: type mismatch resolving `<std::slice::Iter<'_, &str> as IntoIterator>::Item == &str`
--> src/main.rs:251:53
|
251 | for line in content.split('\n').into_iter().chain((&["output"]).iter()) {
| ^^^^^ expected `&str`, found `str`
|
= note: expected reference `&&str`
found reference `&str`
还有其他错误指的是同一行,它们基本上说的是同一件事。

最佳答案

问题的核心是:

  • (&["output"]).iter()std::slice::Iter<'_, &str>类型,具有Item=&&str
  • content.split('\n')std::str::Split<'_, char>类型,具有Item=&str

  • 因此项目类型不匹配。如果使类型与要编译的类型匹配,则IMO最简单的方法是在数组上使用map取消对每个字符串的引用。
        for line in content
    .split('\n')
    .chain((&["output"]).iter().map(|s|*s)) {
    println!("line={}",line);
    }

    我通过插入 let q:() = ...形式的行发现了这一点,这给了我
    21 |     let q:() = (&["output"]).iter();   
    | -- ^^^^^^^^^^^^^^^^^^^^ expected `()`, found struct `std::slice::Iter`
    | |
    | expected due to this
    |
    = note: expected unit type `()`
    found struct `std::slice::Iter<'_, &str>`
    22 |     let q:() = content.split('\n');
    | -- ^^^^^^^^^^^^^^^^^^^ expected `()`, found struct `std::str::Split`
    | |
    | expected due to this
    |
    = note: expected unit type `()`
    found struct `std::str::Split<'_, char>`
    然后跟着 let q: <X as Iterator>::Item = ()
    23 |     let q: <std::slice::Iter<&str> as Iterator>::Item = ();
    | ------------------------------------------ ^^ expected `&&str`, found `()`
    24 |     let q: <std::str::Split<char> as Iterator>::Item = ();
    | ----------------------------------------- ^^ expected `&str`, found `()`

    关于rust - 在String.split之后使用链使用rust ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64997961/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com