Implementation

Similar to functions, implementations require care to remain generic.

1. struct S; // Concrete type `S`
2. struct GenericVal<T>(T,); // Generic type `GenericVal`

4. // impl of GenericVal where we explicitly specify type parameters:
5. impl GenericVal<f32> {} // Specify `f32`
6. impl GenericVal<S> {} // Specify `S` as defined above

8. // `<T>` Must precede the type to remain generic
9. impl <T> GenericVal<T> {}
1. struct Val {
2. val: f64
3. }

5. struct GenVal<T>{
6. gen_val: T
7. }

9. // impl of Val
10. impl Val {
11. fn value(&self) -> &f64 { &self.val }
12. }

14. // impl of GenVal for a generic type `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. }

See also:

functions returning references, impl, and struct