繁体   English   中英

Vec<&str>` 不能从 () 类型的元素上的迭代器构建

[英]Vec<&str>` cannot be built from an iterator over elements of type ()

我是 rust 新手,无法弄清楚为什么我无法在地图后收集:

fn spin_words(words: &str) -> String {
    let split = words.split(" ");
    let mut spinned: Vec<&str> = split
        .into_iter()
        .map(|x: &str| {
            if (x.len() >= 5) {
                x.to_string()
                    .chars()
                    .rev()
                    .collect::<String>()
                    .push_str(" ")
            } else {
                x.to_string().push_str(" ")
            }
        })
        .collect();

    //just returning empty string for the compiler
    "".to_string()
}

我不得不进行以下调整:

  1. 收集到Vec<String> ,因为无论如何你都会构造String对象,所以你必须在向量中拥有它们
  2. 您可以将.chars()迭代器与其他迭代器链接起来,然后收集到String中,而不是实例化一个String并使用数据扩展它.push_str() 请注意, .push_str()也是一种有效的方法,但它会更冗长,因为String::push_str()不返回任何内容,因此您必须创建一些中间变量来保存您的字符串。
fn spin_words(words: &str) -> String {
    let split = words.split(" ");
    let mut spinned: Vec<String> = split
        .into_iter()
        .map(|x: &str| {
            if (x.len() >= 5) {
                x.chars()
                 .rev()
                 .chain(" ".chars())
                 .collect::<String>()
            } else {
                x.chars().chain(" ".chars()).collect::<String>()
            }
        })
        .collect();

    //just returning empty string for the compiler
    "".to_string()
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM