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.

  1. auto nullable(T t)
  2. auto nullable(T t)
    nullable
    (
    alias nullValue
    T
    )
    (
    T t
    )
    if (
    is(typeof(nullValue) == T)
    )
  3. struct Nullable(T, T nullValue)

Parameters

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.

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