rust - 为什么编译器阻止我对使用 collect() 创建的 Vec 使用推送?

标签 rust collect

以下编译:

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")
}

以下不是 ( see 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
}

编译器告诉我

error[E0599]: no method named `join` found for type `()` in the current scope
 --> src/lib.rs:9:10
  |
9 |         .join("\n");
  |          ^^^^

如果我尝试仅使用 push 进行组合,我会遇到相同类型的错误.

我期望的是 collect返回 B , 又名 Vec<String> . Vec不是 () , 和 Vec当然有我想包含在组合函数列表中的方法。

为什么我不能组合这些函数?解释可能包括描述在 collect() 之后终止表达式的“魔力”让编译器实例化 Vec当我用 push 作曲时不会发生这种情况等等

最佳答案

如果您阅读 documentation for Vec::push并查看方法的签名,您将了解到它不返回 Vec:

pub fn push(&mut self, value: T)

由于没有明确的返回类型,返回类型是单元类型 ()() 上没有名为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"]));
}

另见:

关于rust - 为什么编译器阻止我对使用 collect() 创建的 Vec 使用推送?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56362084/

相关文章:

struct - 如何从不同的模块实例化一个公共(public)元组结构(带有私有(private)字段)?

rust - RUST 中这些行之间有什么区别?

python - numpy - 返回索引如果值在 3d 数组之一

R - tbl/collect 有时很慢

c# - 垃圾收集器是否受益于对 Collect 和 WaitForPendingFinalizers() 的多次调用?

oracle sql : collect aggregation

string - 使用 `pop3::POP3Stream::connect` 连接到给定 `host` 的运行时?

rust - 如何处理或测试某个类型是否是 Rust 宏中的选项?

rust - 如何实现一个允许为字段赋值的过程宏?

grails - Grails:ArrayList-检索速度