Keyword to avoid not null references

Jesse Phillips jessekphillips+D at gmail.com
Sun Apr 22 09:59:04 PDT 2012


On Saturday, 21 April 2012 at 22:18:02 UTC, Adam D. Ruppe wrote:
> We can do not null in the library reasonably
> well. I have a basic one in github:
>
> https://github.com/D-Programming-Language/phobos/pull/477

I'm thinking those interested in not null will want something 
similar to the maybe type. As such checkNotNull shoud be more 
than throwing an exception. I have tried this, but it should get 
some constraints. Also wouldn't the new lambda syntax look nice 
with null here: null => unsafe(a)?

import std.stdio;

void main() {
     int* a;
     int i = 5;

     checkNull!(
               t => safe(t),
               () { unsafe(a); })
         (a);

     a = &i;

     checkNull!(
                t => safe(t))
         (a);

}

void checkNull(alias nn, alias n = () {}, T)(T a) {
     if(a !is null)
         nn(assumeNotNull(a));
     else
         n();
}


void safe(NotNull!(int*) i) {
     writeln(*i);
}

void unsafe(int* i) {
     writeln(i);
}



More information about the Digitalmars-d-learn mailing list