impl_with_argument.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. // RUN: %{explorer-run}
  7. // RUN: %{explorer-run-trace}
  8. // CHECK:STDOUT: result: 0
  9. package ExplorerTest api;
  10. interface Vector {
  11. fn Zero() -> Self;
  12. fn Add[me: Self](b: Self) -> Self;
  13. fn Scale[me: Self](v: i32) -> Self;
  14. }
  15. class Point(T:! Type) {
  16. var x: T;
  17. var y: T;
  18. }
  19. // Can implement `Vector` for just `Point(i32)`, not all `Point(T)`.
  20. external impl Point(i32) as Vector {
  21. fn Zero() -> Point(i32) {
  22. return {.x = 0, .y = 0};
  23. }
  24. fn Add[me: Point(i32)](b: Point(i32)) -> Point(i32) {
  25. return {.x = me.x + b.x, .y = me.y + b.y};
  26. }
  27. fn Scale[me: Point(i32)](v: i32) -> Point(i32) {
  28. return {.x = me.x * v, .y = me.y * v};
  29. }
  30. }
  31. fn AddAndScaleGeneric[T:! Vector](a: T, s: i32) -> T {
  32. return a.Add(T.Zero()).Scale(s);
  33. }
  34. fn Main() -> i32 {
  35. var a: Point(i32) = {.x = 2, .y = 1};
  36. var p: Point(i32) = AddAndScaleGeneric(a, 5);
  37. return p.x - 10;
  38. }