rust学习笔记-turbofish
啥是turbofish?
下面代码是一个iterator、map、collect的典型应用
fn reverse_words(str: &str) -> String {
str.to_string()
.split(" ")
.map(|sub| sub.chars().rev().collect())
.collect::<Vec<String>>()
.join(" ")
}
collect::<Vec
Because collect() is so general, it can cause problems with type inference. As such, collect() is one of the few times you’ll see the syntax affectionately known as the ‘turbofish’: ::<>. This helps the inference algorithm understand specifically which collection you’re trying to collect into.
更多细节https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.collect
这个文档里面说了这是一个‘turbofish’: ::<>,用来告诉编译器我们要collect的对象类型。你还别说::<>真像一条鱼。如果你把这条鱼去掉,语法检查会很贴心的告诉你要加上去,在这种它无法判定类型的场景。
再来个例子加深一下记忆:
fn main () {
let a = (0..255).sum(); //error, cannot infer type
let b = (0..255).sum::<u32>();
let c: u32 = (0..255).sum();
}
代码就不解释了,大家自己跑一下