实现
和函数类似,实现(implementation)也需要关注保持泛型。(原文:Similar to functions, implementations require care to remain generic.)
1. struct S; // 具体类型 `S`
2. struct GenericVal<T>(T,); // 泛型类型 `GenericVal`
4. // GenericVal 的实现,此处我们显式地指定了类型参量:
5. impl GenericVal<f32> {} // 指定 `f32` 类型
6. impl GenericVal<S> {} // 指定为上面定义的 `S`
8. // `<T>` 必须在类型之前给出来以保持泛型。
9. // (原文:`<T>` Must precede the type to remain generic)
10. impl <T> GenericVal<T> {}
1. struct Val {
2. val: f64
3. }
5. struct GenVal<T>{
6. gen_val: T
7. }
9. // Val 的实现(impl)
10. impl Val {
11. fn value(&self) -> &f64 { &self.val }
12. }
14. // GenVal 针对泛型类型 `T` 的实现
15. impl <T> GenVal<T> {
16. fn value(&self) -> &T { &self.gen_val }
17. }
19. fn main() {
20. let x = Val { val: 3.0 };
21. let y = GenVal { gen_val: 3i32 };
23. println!("{}, {}", x.value(), y.value());
24. }
