class_function.carbon 937 B

12345678910111213141516171819202122232425262728293031323334353637383940
  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 {
  14. var x: i32;
  15. var y: i32;
  16. impl Point as Vector {
  17. fn Zero() -> Point {
  18. return {.x = 0, .y = 0};
  19. }
  20. fn Add[self: Point](b: Point) -> Point {
  21. return {.x = self.x + b.x, .y = self.y + b.y};
  22. }
  23. fn Scale[self: Point](v: i32) -> Point {
  24. return {.x = self.x * v, .y = self.y * v};
  25. }
  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 = {.x = 2, .y = 1};
  33. var p: Point = AddAndScaleGeneric(a, 5);
  34. return p.x - 10;
  35. }