Motive behind !empty() with front() instead of Optional front()

Nick Treleaven nick at geany.org
Fri Mar 26 15:02:27 UTC 2021


On Friday, 26 March 2021 at 13:23:25 UTC, Per Nordlöw wrote:
> A D specific solution could be to add compiler diagnostics that 
> checks whether a call to `x.front` and x.popFront() is guarded 
> by an `if (!x.empty)`. Provided no mutation has happened since 
> the call to !empty and `x` is not accessible via other threads.

// in @safe code
scope p = &r;
if (!r.empty) {
   p.popFront;
   r.front.writeln; // oops
}

I don't think it's practical for the compiler to detect more 
complicated variants of the above. The beauty of languages with 
compile-time checked optional types is that the value has to 
exist in order to unwrap the optional.


More information about the Digitalmars-d mailing list