param_impl.carbon 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. //
  5. // NOAUTOUPDATE
  6. package ExplorerTest api;
  7. interface Number {
  8. fn Zero() -> Self;
  9. fn Add[self: Self](other: Self) -> Self;
  10. }
  11. class Point(T:! Number) {
  12. var x: T;
  13. var y: T;
  14. }
  15. impl i32 as Number {
  16. fn Zero() -> i32 { return 0; }
  17. fn Add[self: i32](other: i32) -> i32 { return self + other; }
  18. }
  19. impl forall [U:! Number] Point(U) as Number {
  20. fn Zero() -> Point(U) { return {.x = U.Zero(), .y = U.Zero() }; }
  21. fn Add[self: Point(U)](other: Point(U)) -> Point(U) {
  22. return {.x = self.x.Add(other.x), .y = self.y.Add(other.y)};
  23. }
  24. }
  25. fn Sum[E:! Number](x: E, y: E) -> E {
  26. var total: E = E.Zero();
  27. total = total.Add(x);
  28. total = total.Add(y);
  29. return total;
  30. }
  31. fn Main() -> i32 {
  32. var p: Point(i32) = {.x = 1, .y = 2};
  33. var q: Point(i32) = {.x = 4, .y = 3};
  34. var r: Point(i32) = Sum(p, q);
  35. return r.x - r.y;
  36. }
  37. // CHECK:STDOUT: result: 0