class_function.carbon 941 B

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