# Option\<T\>

`Option<T>` represents a present value, `Some(T)`, or an absent value, `None`.
The prelude does not declare an `unwrap` method.

<!-- Legacy section anchors retained for existing links. -->
<a id="variants"></a>
<a id="construction"></a>
<a id="core-query-methods"></a>
<a id="issome-and-isnone"></a>
<a id="or-extract-value-with-fallback"></a>
<a id="orelse-extract-with-computed-fallback"></a>
<a id="transformations"></a>
<a id="map-transform-the-contained-value"></a>
<a id="andthen-chain-fallible-operations"></a>
<a id="filter-conditional-keep"></a>
<a id="or-and-orelse-fallback-options"></a>
<a id="working-with-references"></a>
<a id="best-practices"></a>

## Methods and types

These signatures summarize `lib/runtime/VexArch/src/prelude/option.vx`. Methods
with a by-value receiver consume the option according to its payload's ownership
rules; `isSome`, `isNone`, `clone`, and `asRef` borrow it. `Option<T>` is Copy
only when its concrete payload supports Copy.

| Method | Signature and result |
| --- | --- |
| `isSome`, `isNone` | `(&Option<T>) -> bool` |
| `or` | `(Option<T>, T) -> T`: value or fallback payload |
| `orElse`, `rescue` | `(Option<T>, fn(): T) -> T`: value or computed fallback payload |
| `map` | `(Option<T>, fn(T): U) -> Option<U>` |
| `flatMap` | `(Option<T>, fn(T): Option<U>) -> Option<U>` |
| `filter` | `(Option<T>, fn(T): bool) -> Option<T>` |
| `clone` | `(&Option<T>) -> Option<T>` where `T: Clone` |
| `asRef` | `(&Option<T>) -> Option<&T>` |
| `asMut` | `(&Option<T>!) -> Option<&T!>` |
| `take` | `fn !(self: &Option<T>!) take(): Option<T>` |
| `replace` | `fn !(self: &Option<T>!) replace(value: T): Option<T>` |

`or` does **not** take another `Option<T>` as a fallback for an `Option<T>`;
its fallback is the payload `T`. Likewise, `orElse` returns `T`, not another
option. Use `match` when selecting between optional sources. `flatMap` is the
name declared for Option-returning composition; the prelude does not declare
an `andThen` alias. It also does not declare `okOr` or `okOrElse`; use an
explicit `match` for conversions instead of assuming those methods exist.
`take` returns the old option and leaves `None` behind. `replace(value)`
returns the old option and leaves `Some(value)`. They use the mutating `fn !` marker. Check their ownership
effects before using the old or replacement value; this marker is distinct
from an `unsafe fn` declaration.

Options also support `==` when `T: Eq`: two absent options compare equal;
two present options compare their payloads; a present and absent option differ.

## A runnable example

```vex [option-example.vx]
fn even_half(n: i32): Option<i32> {
    if n % 2 == 0 { return Some(n / 2); }
    return None;
}
fn main(): i32 {
    let value: Option<i32> = Some(10);
    let missing: Option<i32> = None;
    $println(value.isSome());
    $println(missing.isNone());
    $println(value.or(99));
    $println(missing.orElse(|| 7));
    let doubled: Option<i32> = value.map(|n: i32| n * 2);
    $println(doubled.or(0));
    let half: Option<i32> = value.flatMap(even_half);
    $println(half.or(0));
    let filtered: Option<i32> = value.filter(|n: i32| n > 20);
    $println(filtered.or(-1));
    return 0;
}
```

Run `vex run option-example.vx`. The expected stdout is:

```text
true
true
10
7
20
5
-1
```

The closures use explicit parameter types. Some unannotated closures are
inferred successfully, while others are not; annotate a parameter when
inference is insufficient. See [Closures](closures.md#type-inference).

<a id="the-rescue-operator"></a>
<a id="vs"></a>
<a id="pattern-matching"></a>
<a id="converting-to-from-result"></a>
<a id="common-patterns"></a>
<a id="default-value-with-side-effect"></a>
<a id="chaining-multiple-option-operations"></a>
<a id="conditional-execution"></a>
<a id="comparison-with-null"></a>

## Fallback and propagation

A normal function argument such as `option.or(expensive())` is evaluated before
calling `or`, even if the option is `Some`. The callback passed to `orElse` is
called only for `None`. For the `??` operator, `option ?? expensive()`
also evaluates the right side only for `None`; `option !> || expensive()` is
another fallback form. See [Operators](../advanced/operators-reference.md)
for `??`, `!>`, and `?`.

A `match` makes the paths explicit and can construct a result:

```vex
fn require_value(option: Option<i32>): Result<i32, i32> {
    return match option {
        Some(value) => Ok(value),
        None => Err(1),
    };
}
```

A `?` applied to `None` in a function returning an `Option` propagates `None`.

## Collecting options

The following complete example uses an explicit `match` and a `Vec<i32>` to compact present values. It covers mixed, all-present, and all-absent input. The result contains the payloads themselves; retaining `Some` wrappers would produce a different element type.

```vex [collect-options.vx]
fn collect(values: [Option<i32>; 4]): Vec<i32> {
    let! output = Vec.new<i32>();
    let! i: usize = 0;
    while i < 4 {
        match values[i] {
            Some(value) => { output.push(value); },
            None => {},
        };
        i = i + 1;
    }
    return output;
}
fn main(): i32 {
    let mixed: [Option<i32>; 4] = [Some(1), Some(2), None, Some(4)];
    let all: [Option<i32>; 4] = [Some(1), Some(2), Some(3), Some(4)];
    let none: [Option<i32>; 4] = [None, None, None, None];
    let a = collect(mixed);
    let b = collect(all);
    let c = collect(none);
    if a.len() != 3 || a[0] != 1 || a[1] != 2 || a[2] != 4 { return 1; }
    if b.len() != 4 || b[0] != 1 || b[1] != 2 || b[2] != 3 || b[3] != 4 { return 2; }
    if c.len() != 0 { return 3; }
    $println(a.len()); $println(a[0]); $println(a[1]); $println(a[2]);
    $println(b.len()); $println(b[0]); $println(b[1]); $println(b[2]); $println(b[3]);
    $println(c.len());
    return 0;
}
```

The mixed output has length 3 and values `1, 2, 4`; the all-present output has length 4 and values `1, 2, 3, 4`; the all-absent output has length 0. The program prints those lengths and values in that order and exits 0; it returns a nonzero code if a check fails.

Replacing each `None` with `0` instead would preserve positions and produce `[1, 2, 0, 4]`; that is a different operation.

## Transfer an owning payload out of a reusable slot

`take` is useful for a pending task or cached value that is consumed once.
`replace` installs a new payload and returns the old one, allowing the caller
to process or release it explicitly. Neither operation clones the payload.

```vex [optional-slot.vx]
fn runNext(pending: &Option<string>!): usize {
    return match pending.take() {
        Some(command) => { $println(command); command.len() },
        None => 0,
    };
}
fn main(): i32 {
    let! pending: Option<string> = Some("deploy".toString());
    let previous = pending.replace("backup".toString());
    match previous {
        Some(command) => { $println(f"replaced: {command}"); },
        None => { return 1; },
    };
    if runNext(&pending!) != 6 || pending.isSome() { return 2; }
    if runNext(&pending!) != 0 { return 3; }
    let empty = pending.replace("verify".toString());
    if empty.isSome() || runNext(&pending!) != 6 { return 4; }
    return 0;
}
```

The program prints `replaced: deploy`, `backup`, and `verify`, then exits 0.
Here processing a command prints its name. After `runNext`, the slot contains
`None`, so a second call does no work. Replacing that empty slot installs a new
owned string and returns `None`. Each successful `take` transfers the string
to the match arm; the slot no longer owns that string.

## Related pages

- [Result](result-api.md)
- [Pattern Matching](pattern-matching.md)
- [Error Handling](../error-handling.md)

<!--
Legacy checker fixture; historical behavior and migration plan are recorded in
../../../audit/2026-11-13-language-code-gaps.md. This is not rendered guidance.
```vex [option-filter-rejected.vx]
fn present(value: &Option<i32>): bool { return value.isSome(); }
fn main(): i32 {
    let! values = Vec.new<Option<i32>>();
    values.push(Some(1));
    let filtered = values.filter(present);
    $println(filtered.len());
    return 0;
}
```
-->
