optional.carbon 760 B

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