draft proposal for Sum Types for D

Walter Bright newshound2 at digitalmars.com
Fri Dec 2 05:23:53 UTC 2022


On 11/29/2022 6:45 AM, Timon Gehr wrote:
> BTW: I understand extraordinarily well where the desire for supporting an 
> explicitly nullable pointer comes from, but I worry that integrating it into the 
> more general syntax implicitly is a bit too cute. It will lead to bad 
> interactions in generic code.
> 
> E.g.:
> 
> sumtype WithDefault(T){
>      Default;
>      T Value;
> }
> 
> A user does not expect this to behave specially if `T` is a pointer. Generic 
> code would have to explicitly check for that case and manually undo the rewrite 
> in the library. I don't want to read the resulting unwieldy Phobos code.

In defense, I would add that Rust appears to just the same thing. Except that 
Rust pointers can't be null. I do understand the notion that a quirk may cause 
problems.


> Explicitly nullable pointers are too good of a feature to just give up though, 
> so instead, you could introduce explicit syntax for the null check.
> 
> E.g.:
> 
> sumtype Nullable{
>      Null,
>      int* Ptr;
>      invariant(Ptr !is null);
> }

I know, but the syntax is a bit unappealing. How about:

sumtype Nullable { Null = null, int* Ptr }

where the `= null` triggers the special case, as it is not an integer.

> Note that with the semantics where a bad member access is a runtime error, you 
> don't gain much over just using a raw pointer.

What you get is a better error message than seg fault.

> Therefore, I really think D should statically enforce that the user checks the tag.

The user isn't going to want to do that if he knows the tag is correct. Array 
buffer overflow checks are also hidden from the user.



More information about the Digitalmars-d mailing list