Nullable

Just like Nullable!T, except that the null state is defined as a particular value. For example, Nullable!(uint, uint.max) is an uint that sets aside the value uint.max to denote a null state. Nullable!(T, nullValue) is more storage-efficient than Nullable!T because it does not need to store an extra bool.

Constructors

this
this(T value)

Constructor initializing this with value.

Alias This

get

Implicitly converts to T. this must not be in the null state.

Members

Functions

nullify
void nullify()

Forces this to the null state.

opAssign
void opAssign(T value)

Assigns value to the internally-held state. If the assignment succeeds, this becomes non-null. No null checks are made. Note that the assignment may leave this in the null state.

Properties

get
inout(T) get [@property getter]

Gets the value. this must not be in the null state. This function is also called for the implicit conversion to T.

isNull
bool isNull [@property getter]

Check if this is in the null state.

Examples

1 Nullable!(size_t, size_t.max) indexOf(string[] haystack, string needle)
2 {
3     //Find the needle, returning -1 if not found
4 
5     return Nullable!(size_t, size_t.max).init;
6 }
7 
8 void sendLunchInvite(string name)
9 {
10 }
11 
12 //It's safer than C...
13 auto coworkers = ["Jane", "Jim", "Marry", "Fred"];
14 auto pos = indexOf(coworkers, "Bob");
15 if (!pos.isNull)
16 {
17     //Send Bob an invitation to lunch
18     sendLunchInvite(coworkers[pos]);
19 }
20 else
21 {
22     //Bob not found; report the error
23 }
24 
25 //And there's no overhead
26 static assert(Nullable!(size_t, size_t.max).sizeof == size_t.sizeof);
import std.exception : assertThrown;

Nullable!(int, int.min) a;
assert(a.isNull);
assertThrown!Throwable(a.get);
a = 5;
assert(!a.isNull);
assert(a == 5);
static assert(a.sizeof == int.sizeof);
auto a = nullable!(int.min)(8);
assert(a == 8);
a.nullify();
assert(a.isNull);

Meta

Suggestion Box / Bug Report