Note: None of this capability is currently implemented.
The Option type is useful when we want to express the idea that we may or may not have a value of a certain type. null is the name used to represent the absence of a value. some[x] represents some specific value. Nullable values are needed so often that special syntax exist to make them easier to use.
To declare a nullable type, simply put a question mark before the type. For example:
mut maybeInt ?i32 = null // Initial value indicates the absence of a value if maybeInt == null // or: if !maybeInt maybeInt = 4 // Give it the value 4
If the type of a declared variable is omitted but an initial value is specified, the initial value needs to be wrapped in the some constructor:
mut maybeInt = some
Nullable References Nullable references take no more space than regular references. The null reference value is just a non-addressable address (typically, 0).
The ? and || operators that are so helpful for Result values can also be applied to nullable values.
Give null a default value
Use the || operator to establish a real value in the event of null.
imm val = maybeInt || 0
val will be the value of maybeInt if it is not null. Otherwise it will be 0. The value to the right of the operator cannot be a nullable type, and its type must match that of a valid value for the nullable value on the left.
Handle null as an exception
Use the ? operator to treat a null value as an exception.
imm val = maybeInt?
val will be the value of maybeInt if it is not null. Otherwise it will panic.
If a catch null handler is provided, it will be invoked instead of a panic.
A variation of the method call operator allows safe method calls on a nullable value:
imm x = maybePoint?.dist
In effect, this propagates nullability from maybePoint to x. If maybePoint holds a valid value, the method is called and its return value is wrapped as nullable. If maybePoint is null, then so will x be.