知识卡片
闭包推断具体类型
Rust 能根据闭包的上下文推断参数及返回值类型。|x| x 可根据调用推断成 String -> String,随后不能再用它接收整数。若需要明确接口或推断信息不足,可以显式写参数及返回类型。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- 函数式语言特性:迭代器与闭包 Closure Type Inference and Annotation · 查看原书依据
The first time we call example_closure with the String value, the compiler infers the type of x and the return type of the closure to be String. Those types are then locked into the closure in example_closure, and we get a type error when we next try to use a different type with the same closure.
参考来源
- 位置:《The Rust Programming Language(第2版)》第13章 函数式语言特性:迭代器与闭包(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c13.xhtml`,块 0041)
- 结论依据:原文用先传 String、再传整数的例子展示同一闭包实例的类型约束。
- 原始内容:The first time we call example_closure with the String value, the compiler infers the type of x and the return type of the closure to be String. Those types are then locked into the closure in example_closure, and we get a type error when we next try to use a different type with the same closure.