Comparison of struct with Nullable member

Nicholas Wilson via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jul 17 06:31:30 PDT 2015


On Friday, 17 July 2015 at 12:18:56 UTC, TC wrote:
> Hello,
> I came around a strange behavior and I'm not sure if it is a 
> bug or feature.
>
> import std.typecons : Nullable;
> struct Foo
> {
> 	string bar;
> 	Nullable!int baz;
> }
>
> auto a = Foo("bb");
> auto b = Foo("bb");
> assert(a == b);
>
> This ends up with: Called `get' on null Nullable!int
>
> But if I change bar to be an int for example, than it passes ok.
> I would expect this to pass ok.
>
> Tested on dmd 2.067.1 win64

what is happening is the complier generated default opEquals is 
accessing the payload for Nullable!T without checking for null 
(which as you've written `Foo("bb")` this constructs a and b as 
`Foo("bb",(Nullable!int).init)` i.e. in the null state)

why nullables don't automatically check for null when comparing 
for equality idk.

you can make this work by defining your own opEquals that 
explicitly checks for nulls.




More information about the Digitalmars-d-learn mailing list