Generic Methods

You can declare a generic type on your impl block:

  1. #[derive(Debug)]
  2. struct Point<T>(T, T);
  3. impl<T> Point<T> {
  4. fn x(&self) -> &T {
  5. &self.0 // + 10
  6. }
  7. // fn set_x(&mut self, x: T)
  8. }
  9. fn main() {
  10. let p = Point(5, 10);
  11. println!("p.x = {}", p.x());
  12. }
  • Q: Why T is specified twice in impl<T> Point<T> {}? Isn’t that redundant?
    • This is because it is a generic implementation section for generic type. They are independently generic.
    • It means these methods are defined for any T.
    • It is possible to write impl Point<u32> { .. }.
      • Point is still generic and you can use Point<f64>, but methods in this block will only be available for Point<u32>.