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();
}
代码就不解释了,大家自己跑一下
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix