以下编译:
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/