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();
}

代码就不解释了,大家自己跑一下

posted @   西门飘柔  阅读(403)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示