generic_fun_and_class.carbon 933 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  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. // RUN: %{explorer-run}
  7. // RUN: %{explorer-run-trace}
  8. // CHECK:STDOUT: result: 0
  9. package ExplorerTest api;
  10. interface Number {
  11. fn Zero() -> Self;
  12. fn Add[self: Self](other: Self) -> Self;
  13. }
  14. class Point(T:! Number) {
  15. var x: T;
  16. var y: T;
  17. }
  18. fn Origin[U :! Number](other: U) -> Point(U) {
  19. return {.x = U.Zero(), .y = U.Zero()};
  20. }
  21. fn Clone[U :! Number](other: Point(U)) -> Point(U) {
  22. return {.x = other.x, .y = other.y};
  23. }
  24. fn SumXY[U :! Number](other: Point(U)) -> U {
  25. return other.x.Add(other.y);
  26. }
  27. external impl i32 as Number {
  28. fn Zero() -> i32 { return 0; }
  29. fn Add[self: i32](other: i32) -> i32 { return self + other; }
  30. }
  31. fn Main() -> i32 {
  32. var p: Point(i32) = Origin(0);
  33. return SumXY(Clone(p));
  34. }