实现

和函数类似,impl 块要想实现泛型,也需要很仔细。

  1. struct S; // 具体类型 `S`
  2. struct GenericVal<T>(T,); // 泛型类型 `GenericVal`
  3. // GenericVal 的 `impl`,此处我们显式地指定了类型参数:
  4. impl GenericVal<f32> {} // 指定 `f32` 类型
  5. impl GenericVal<S> {} // 指定为上面定义的 `S`
  6. // `<T>` 必须在类型之前写出来,以使类型 `T` 代表泛型。
  7. impl <T> GenericVal<T> {}
  1. struct Val {
  2. val: f64
  3. }
  4. struct GenVal<T>{
  5. gen_val: T
  6. }
  7. // Val 的 `impl`
  8. impl Val {
  9. fn value(&self) -> &f64 { &self.val }
  10. }
  11. // GenVal 的 `impl`,指定 `T` 是泛型类型
  12. impl <T> GenVal<T> {
  13. fn value(&self) -> &T { &self.gen_val }
  14. }
  15. fn main() {
  16. let x = Val { val: 3.0 };
  17. let y = GenVal { gen_val: 3i32 };
  18. println!("{}, {}", x.value(), y.value());
  19. }

参见:

返回引用的函数, impl, 和 struct