Defines a value paired with a distinctive "null" state that denotes
the absence of a value. If default constructed, a Nullable!Tobject starts in the null state. Assigning it renders it
non-null. Calling nullify can nullify it again.
Assigns value to the internally-held state. If the assignment
succeeds, this becomes non-null.
Example
struct CustomerRecord
{
string name;
string address;
int customerNum;
}
Nullable!CustomerRecord getByName(string name)
{
//A bunch of hairy stuff
return Nullable!CustomerRecord.init;
}
auto queryResult = getByName("Doe, John");
if (!queryResult.isNull)
{
//Process Mr. Doe's customer record
auto address = queryResult.address;
auto customerNum = queryResult.customerNum;
//Do some things with this customer's info
}
else
{
//Add the customer to the database
}
Struct 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.
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.
Parameters
Name
Description
T
The wrapped type for which Nullable provides a null value.
nullValue
The null value which denotes the null state of this
Nullable. Must be of type T.
Example
Nullable!(size_t, size_t.max) indexOf(string[] haystack, string needle)
{
//Find the needle, returning -1 if not found
return Nullable!(size_t, size_t.max).init;
}
void sendLunchInvite(string name)
{
}
//It's safer than C...
auto coworkers = ["Jane", "Jim", "Marry", "Fred"];
auto pos = indexOf(coworkers, "Bob");
if (!pos.isNull)
{
//Send Bob an invitation to lunch
sendLunchInvite(coworkers[pos]);
}
else
{
//Bob not found; report the error
}
//And there's no overhead
static assert(Nullable!(size_t, size_t.max).sizeof == size_t.sizeof);