generic_method_impl.carbon 1014 B

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