impl_with_argument.carbon 1.0 KB

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