generic_method_impl.carbon 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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: 3
  9. package ExplorerTest api;
  10. class Cell(T:! type) {
  11. fn Create(x: T) -> Cell(T) { return { .data = x }; }
  12. fn Get[self: Self]() -> T {
  13. return self.data;
  14. }
  15. fn Put[addr self: Self*](x: T) {
  16. (*self).data = x;
  17. }
  18. fn Update[addr self: Self*, U:! ImplicitAs(T)](x: U) {
  19. (*self).data = x;
  20. }
  21. fn CreateOther[self: Self, U:! type](x: U) -> Cell(U) {
  22. return {.data = x};
  23. }
  24. var data: T;
  25. }
  26. class Integer {
  27. var int: i32;
  28. }
  29. fn Main() -> i32 {
  30. var i: Integer = {.int = 1};
  31. var c: Cell(Integer) = Cell(Integer).Create(i); // c contains 1
  32. i = {.int = 2};
  33. var j: Integer = c.Get(); // j == 1
  34. c.Put(i); // c contains 2
  35. c.Update(j); // c contains 1
  36. var d: Cell(Integer) = c.CreateOther(i); // d contains 2
  37. return c.data.int + d.data.int;
  38. }