测试用例:单位明确
通过使用幻影类型参数实现 Add
,可以研究一种有用的单位转换方法。下面将研究 Add
trait
// This construction would impose: `Self + RHS = Output`
// where RHS defaults to Self if not specified in the implementation.
pub trait Add<RHS = Self> {
type Output;
fn add(self, rhs: RHS) -> Self::Output;
}
// `Output` must be `T<U>` so that `T<U> + T<U> = T<U>`.
impl<U> Add for T<U> {
type Output = T<U>;
...
}
完整实现
另请参阅
借用 (&
), 约束 (X: Y
), enum, impl & self, 重载, ref, 特征 (X for Y
), 和 元组结构体。