optional.carbon 877 B

12345678910111213141516171819202122232425262728293031
  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. // INCLUDE-FILE: toolchain/testing/testdata/min_prelude/parts/bool.carbon
  6. // INCLUDE-FILE: toolchain/testing/testdata/min_prelude/parts/destroy.carbon
  7. // --- min_prelude/parts/optional.carbon
  8. package Core library "prelude/parts/optional";
  9. import library "prelude/parts/bool";
  10. import library "prelude/parts/destroy";
  11. class Optional(T:! type) {
  12. fn None() -> Self {
  13. returned var me: Self;
  14. me.has_value = false;
  15. return var;
  16. }
  17. fn Some(value: T) -> Self {
  18. return {.has_value = true, .value = value};
  19. }
  20. fn HasValue[self: Self]() -> bool { return self.has_value; }
  21. fn Get[self: Self]() -> T { return self.value; }
  22. var has_value: bool;
  23. var value: T;
  24. }