param_impl_with_self.carbon 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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. // AUTOUPDATE
  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. // Allowed: `Self` means `Point(U)` here.
  21. fn Zero() -> Self { return {.x = U.Zero(), .y = U.Zero() }; }
  22. fn Add[self: Self](other: Self) -> Self {
  23. return {.x = self.x.Add(other.x), .y = self.y.Add(other.y)};
  24. }
  25. }
  26. fn Sum[E:! Number](x: E, y: E) -> E {
  27. var total: E = E.Zero();
  28. total = total.Add(x);
  29. total = total.Add(y);
  30. return total;
  31. }
  32. fn Main() -> i32 {
  33. var p: Point(i32) = {.x = 1, .y = 2};
  34. var q: Point(i32) = {.x = 4, .y = 3};
  35. var r: Point(i32) = Sum(p, q);
  36. return r.x - r.y;
  37. }
  38. // CHECK:STDOUT: result: 0