Once#
Primitives for containers that can be written only once. Inspired by OnceCell and LazyCell.
Implementation#
Once takes reference from OnceCell and the current status is as follows:
Reference OnceCell |
Counterpart |
|---|---|
get |
|
get_mut |
|
get_mut_or_init |
|
get_mut_or_try_init |
|
get_or_init |
|
get_or_try_init |
|
into_inner |
|
new |
|
set |
|
take |
|
try_insert |
Once
#
A container that can be written only once.
See OnceCell for more information.
__bool__()
#
Check if the Once container has been set.
Returns:
| Name | Type | Description |
|---|---|---|
is_set |
bool
|
|
__init__()
#
Create an unpopulated Once container.
Returns:
| Name | Type | Description |
|---|---|---|
container |
Once
|
An unpopulated |
get_or_init(f)
#
Get the inner value of the Once container, or initialize it with the given function if no value has been set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
f
|
Callable[[], T]
|
The function to initialize the |
required |
Returns:
| Name | Type | Description |
|---|---|---|
value |
T
|
The inner value (maybe newly set) of the |
set(value)
#
Set the inner value of the Once container.
If a value has already been set, this method currently does nothing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
T
|
The value to set the |
required |
Experimental
This method will return a Result type in the future.
unwrap()
#
Get the inner value of the Once container.
If no value has been set, this method raises a ValueError.
Returns:
| Name | Type | Description |
|---|---|---|
value |
T
|
The inner value of the |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no value has been set. |
Lazy
#
A container that can be lazily initialized only once.
The stored function will be actually called only on the first retrieval, and the result will be cached for consequent calls.
See LazyCell for more information.
Example
__call__()
#
An alias for Lazy.value.
Notice that this operator overloading might be slower than calling value directly.
__init__(f)
#
Create a lazily initialized Lazy container.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
f
|
Callable[[], T]
|
The function to be lazily initialized. |
required |
unwrap()
#
Get the inner value of the Lazy container.
If no value has been set, this method raises a ValueError.
Returns:
| Name | Type | Description |
|---|---|---|
value |
T
|
The lazily initialized value of the |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no value has been set. |
value()
#
Get the inner value of the Lazy container.
If no value has been set, this method initializes the value with the stored function.
Returns:
| Name | Type | Description |
|---|---|---|
value |
T
|
The lazily initialized value of the |