Union untagged_option::UntaggedOption [] [src]

pub union UntaggedOption<T> {
    pub some: T,
    pub none: (),
}

A union which either holds a T or nothing.

This can be seen as a T that may not be properly initialized.

In contrast to Option<T>, this type does not know if it stores a T or not, so it relies on the caller to uphold safety. Consequently, UntaggedOption can be a bit smaller than Option since it never has a discriminant. This makes it useful in resource-constrained environments or other scenarios where the space overhead of Option is significant.

Examples

let mut opt = UntaggedOption::none();

// `opt` didn't hold a value before, so this assigment is fine.
// If it did, the value would be leaked.
opt = UntaggedOption::some("&str stored");

unsafe {
    // Safe: `opt` is now properly initialized and holds a value.
    assert_eq!(opt.as_ref(), &"&str stored");
    let content = opt.take();   // `opt` is now uninitialized/none
}

Safety

Since UntaggedOption does not have a discriminant, the user must know when the option contains a valid value and only call the appropriate methods.

UntaggedOption does not destroy the contained value when dropped (it doesn't know if there is a value), so the user must make sure to manually remove the value by calling take (or only use UntaggedOption with Copy types that do not need to be dropped).

This also applies to assignments: An assignment like opt = UntaggedOption::none() will leak the previously contained value (if any).

Fields

some: T none: ()

Methods

impl<T> UntaggedOption<T>
[src]

[src]

Creates a new UntaggedOption holding no value.

It is not safe to call any method on the resulting UntaggedOption.

[src]

Creates an UntaggedOption containing t.

Note

When the UntaggedOption is dropped, t will not be dropped automatically. You must call take if you need t to be dropped properly.

[src]

Takes the T out of an initialized wrapper, making it uninitialized.

This can be called to drop the contained T.

Safety

Calling this method requires that self holds a valid T. UntaggedOption::some creates such an option.

[src]

Obtains an immutable reference to the contained T.

Safety

Calling this method requires that self holds a valid T. UntaggedOption::some creates such an option.

[src]

Obtains a mutable reference to the contained T.

Safety

Calling this method requires that self holds a valid T. UntaggedOption::some creates such an option.