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