为什么编译器阻止我在使用collect()创建的Vec上使用推?

Edm*_*cho -2 collect rust

编译如下:

pub fn build_proverb(list: &[&str]) -> String {
    if list.is_empty() {
        return String::new();
    }
    let mut result = (0..list.len() - 1)
        .map(|i| format!("For want of a {} the {} was lost.", list[i], list[i + 1]))
        .collect::<Vec<String>>();
    result.push(format!("And all for the want of a {}.", list[0]));
    result.join("\n")
}
Run Code Online (Sandbox Code Playgroud)

以下不是(请参见Playground):

pub fn build_proverb(list: &[&str]) -> String {
    if list.is_empty() {
        return String::new();
    }
    let mut result = (0..list.len() - 1)
        .map(|i| format!("For want of a {} the {} was lost.", list[i], list[i + 1]))
        .collect::<Vec<String>>()
        .push(format!("And all for the want of a {}.", list[0]))
        .join("\n");
    result
}
Run Code Online (Sandbox Code Playgroud)

编译器告诉我

pub fn build_proverb(list: &[&str]) -> String {
    if list.is_empty() {
        return String::new();
    }
    let mut result = (0..list.len() - 1)
        .map(|i| format!("For want of a {} the {} was lost.", list[i], list[i + 1]))
        .collect::<Vec<String>>();
    result.push(format!("And all for the want of a {}.", list[0]));
    result.join("\n")
}
Run Code Online (Sandbox Code Playgroud)

如果我尝试仅使用编写错误,则会遇到相同类型的错误push

我会想到的是collect回报率B,又名Vec<String>Vec不是()Vec当然还有我想包含在组合函数列表中的方法。

为什么我不能编写这些功能?解释可能包括描述终止表达式的“魔力”,collect()以使编译器以Vec当我使用pushetc 编写时不会发生的方式实例化。

She*_*ter 5

如果您阅读了该文档的文档Vec::push并查看了该方法的签名,则会发现该方法不返回Vec

pub fn push(&mut self, value: T)
Run Code Online (Sandbox Code Playgroud)

由于没有显式的返回类型,因此返回类型为unit type ()。没有调用的方法join()。您将需要多行编写代码。

也可以看看:


我会在功能上写这个:

use itertools::Itertools; // 0.8.0

pub fn build_proverb(list: &[&str]) -> String {
    let last = list
        .get(0)
        .map(|d| format!("And all for the want of a {}.", d));

    list.windows(2)
        .map(|d| format!("For want of a {} the {} was lost.", d[0], d[1]))
        .chain(last)
        .join("\n")
}

fn main() {
    println!("{}", build_proverb(&["nail", "shoe"]));
}
Run Code Online (Sandbox Code Playgroud)

也可以看看: