Creating a NotNull struct
By disabling default construction, we can force initialization of a type. Using this feature, we'll make an object reference that will force the user to check for null before using it.
How to do it…
To create a NotNull struct, perform the following steps:
Create
struct NotNull(T)
with a private member of typeT
.Disable default construction with
@disable this();
.Write a private constructor that takes
T
andassert(t !is null);
.Write a property function that returns the payload and use it with
alias this
.Write a helper
struct CheckNull(T)
, with a memberT
. The memberT
is a property that returnsNotNull!T
and hasopCast(T : bool)
, which checks the payload for null and returnstrue
if it is not null.Write a helper function,
checkNull
, which takes aT
member and returnsCheckNull!T
.Write your functions to accept and return
NotNull!T
whenever possible.Optionally, write a generic factory function that returns
NotNull!T
.Use the function with
if(auto nn = test.checkNull) {...