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