option
A value that may or may not be there, without nulls and without magic numbers such as minus one.
import option
Sometimes the answer from a function is "nothing": a search found no match, or a setting was never given. Returning minus one or an empty string for that is convenient, and later forgotten, and then it is a bug. Option<T> makes it explicit: either there is a value of type T, or there is not.
If the reason for the failure matters as well as its absence, result is the better fit.
Types
Option
struct Option<T>Some or None, so that the two fields always agree.| Name | Type | Description |
|---|---|---|
value | T | The value itself. When present is false this is the zero value of T and means nothing. |
present | bool | True when there is a value. |
import option
func search(names: Vector<str>, wanted: str): option.Option<int>:
each i, name in names:
if name == wanted:
ret option.Some(i)
end
end
ret option.None()
end
func main:
mut names := Vector {} as Vector<str>
defer names.free()
names.push("Ali")
names.push("Maryam")
found := search(names, "Maryam")
missing := search(names, "Reza")
println option.IsSome(found), option.IsNone(found), found.value, found.present
println option.IsSome(missing), option.IsNone(missing)
println option.Unwrap(found), option.Expect(found, "this should have been found")
println option.UnwrapOr(missing, -1)
endFunctions
Some
func Some<T>(x: T): Option<T>The example for this item is shown with the ones above: option-Option.salam
None
func None<T>(): Option<T>T comes from where the value is used, such as the return type of the function.The example for this item is shown with the ones above: option-Option.salam
IsSome
func IsSome<T>(o: Option<T>): boolThe example for this item is shown with the ones above: option-Option.salam
IsNone
func IsNone<T>(o: Option<T>): boolThe example for this item is shown with the ones above: option-Option.salam
UnwrapOr
func UnwrapOr<T>(o: Option<T>, fallback: T): TThe example for this item is shown with the ones above: option-Option.salam
Unwrap
func Unwrap<T>(o: Option<T>): TThe example for this item is shown with the ones above: option-Option.salam
Expect
func Expect<T>(o: Option<T>, msg: str): TUnwrap, but stops with a message of your own when the option is empty; a good message makes the problem easy to find.The example for this item is shown with the ones above: option-Option.salam