【发布时间】:2019-05-29 13:44:51
【问题描述】:
以下编译:
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() 之后终止表达式的“魔力”,以使编译器以我使用push 等编写时不会发生的方式实例化Vec。
【问题讨论】:
-
因为
push()不返回向量