generic_method.carbon 839 B

1234567891011121314151617181920212223242526272829303132333435363738
  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 CreateOther[self: Self, U:! type](x: U) -> Cell(U) {
  16. return {.data = x};
  17. }
  18. var data: T;
  19. }
  20. class Integer {
  21. var int: i32;
  22. }
  23. fn Main() -> i32 {
  24. var i: Integer = {.int = 1};
  25. var c: Cell(Integer) = Cell(Integer).Create(i);
  26. i = {.int = 0};
  27. c.Put(i);
  28. var j: Integer = c.Get();
  29. var d: Cell(Integer) = c.CreateOther(j);
  30. return c.data.int + d.data.int;
  31. }
  32. // CHECK:STDOUT: result: 0