Rust的泛型在编译时单态化,实现零成本抽象。本文详解泛型编程技巧。 ## 泛型函数 ```rust fn largest(list: &[T]) -> &T { let mut largest = &list[0]; for item in &list[1..] { if item > largest { largest = item; } } largest } ``` ## 泛型结构体 ```rust struct Point { x: T, y: T, } impl Point { fn x(&self) -> &T { &self.x } } impl Point { fn distance_from_origin(&self) -> f32 { (self.x.powi(2) + self.y.powi(2)).sqrt() } } ``` ## 类型别名 ```rust type Result = std::result::Result; type IntMap = std::collections::HashMap; ``` ## newtype模式 ```rust struct Millimeters(u32); struct Meters(u32); fn add_mm(a: Millimeters, b: Millimeters) -> Millimeters { Millimeters(a.0 + b.0) } ``` ## 幽灵类型参数 ```rust use std::marker::PhantomData; struct UnitValue { value: f64, _marker: PhantomData, } struct Km; struct Miles; type KmValue = UnitValue; type MilesValue = UnitValue; ``` Rust的泛型通过单态化在编译期展开,运行时没有任何额外开销。