www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - is there a way to use sumtype in `switch/case` (with multiple

reply mw <m g.c> writes:
https://dlang.org/library/std/sumtype.html

seems right now the `match!(...)` template only generate a 
delegate, e.g. suppose the following (silly) code:

```
bool isF(Temperature t) {
   while (true) {
     t.match!(
       (Fahrenheit f) {return true;},
       (_) {return false;}  // I want to return from the func isF, 
not the delegate!
     );
   }
}

enforce( isF(t1));
```

currently, this code will do infinite loop.


I'm wondering if the following are possible:

```
bool isF(Temperature t) {
   while (true) {
     switch (t) {
       case Fahrenheit f: /* do multiple statements of `f` */ 
return true;
       default: return false;
     }
   }
}
```

Or how can I get the `tag` and `storage` myself?

https://github.com/dlang/phobos/blob/a3f22129dd2a134338ca02b79ff0de242d7f016e/std/sumtype.d#L310

Thanks.
Oct 07 2023
parent reply mw <m g.c> writes:
On Saturday, 7 October 2023 at 19:25:51 UTC, mw wrote:
 Or how can I get the `tag` and `storage` myself?

 https://github.com/dlang/phobos/blob/a3f22129dd2a134338ca02b79ff0de242d7f016e/std/sumtype.d#L310
If I add this line to the above func `isF`: ``` writeln(t.tag); ``` it won't compile: sum_type.d(79): Error: no property `tag` for `t` of type `std.sumtype.SumType!(Fahrenheit, Celsius, Kelvin)`
Oct 07 2023
parent mw <m g.c> writes:
On Saturday, 7 October 2023 at 19:30:23 UTC, mw wrote:
 On Saturday, 7 October 2023 at 19:25:51 UTC, mw wrote:
 Or how can I get the `tag` and `storage` myself?

 https://github.com/dlang/phobos/blob/a3f22129dd2a134338ca02b79ff0de242d7f016e/std/sumtype.d#L310
If I add this line to the above func `isF`: ``` writeln(t.tag); ``` it won't compile: sum_type.d(79): Error: no property `tag` for `t` of type `std.sumtype.SumType!(Fahrenheit, Celsius, Kelvin)`
Shouldn't the compiler error message be: t.tag is private? rather than "no property `tag` for `t`"? The tag is stored there, why the programmer cannot inspect it, and get the payload?
Oct 07 2023