param_impl_with_self.carbon 1.1 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. // AUTOUPDATE
  6. // CHECK:STDOUT: result: 0
  7. package ExplorerTest api;
  8. interface Number {
  9. fn Zero() -> Self;
  10. fn Add[self: Self](other: Self) -> Self;
  11. }
  12. class Point(T:! Number) {
  13. var x: T;
  14. var y: T;
  15. }
  16. external impl i32 as Number {
  17. fn Zero() -> i32 { return 0; }
  18. fn Add[self: i32](other: i32) -> i32 { return self + other; }
  19. }
  20. external impl forall [U:! Number] Point(U) as Number {
  21. // Allowed: `Self` means `Point(U)` here.
  22. fn Zero() -> Self { return {.x = U.Zero(), .y = U.Zero() }; }
  23. fn Add[self: Self](other: Self) -> Self {
  24. return {.x = self.x.Add(other.x), .y = self.y.Add(other.y)};
  25. }
  26. }
  27. fn Sum[E:! Number](x: E, y: E) -> E {
  28. var total: E = E.Zero();
  29. total = total.Add(x);
  30. total = total.Add(y);
  31. return total;
  32. }
  33. fn Main() -> i32 {
  34. var p: Point(i32) = {.x = 1, .y = 2};
  35. var q: Point(i32) = {.x = 4, .y = 3};
  36. var r: Point(i32) = Sum(p, q);
  37. return r.x - r.y;
  38. }