泛型函数
Rust supports generics, which lets you abstract algorithms or data structures (such as sorting or a binary tree) over the types used or stored.
/// Pick `even` or `odd` depending on the value of `n`. fn pick<T>(n: i32, even: T, odd: T) -> T { if n % 2 == 0 { even } else { odd } } fn main() { println!("picked a number: {:?}", pick(97, 222, 333)); println!("picked a tuple: {:?}", pick(28, ("dog", 1), ("cat", 2))); }
This slide should take about 5 minutes.
-
Rust 会根据参数类型和返回值推理出 T 的类型。
-
这与 C++ 模板类似,但 Rust 会立即编译部分通用函数,因此该函数必须对所有符合约束条件的类型都有效。例如,请尝试修改
pick
函数,如果n == 0
,则返回even + odd
。即使仅使用带有整数的“pick”实例化,Rust 仍会将其视为无效。C++ 可让您做到这一点。 -
Generic code is turned into non-generic code based on the call sites. This is a zero-cost abstraction: you get exactly the same result as if you had hand-coded the data structures without the abstraction.