Extern 函式
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++ 模板 (template) 類似,但 Rust 會立即對泛型函式進行部分編譯,因此函式必須適用於所有符合限制條件的型別。舉例來說,如果
n == 0,請嘗試修改pick以傳回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.