Remove switch case fallthrough

Ogi ogion.art at gmail.com
Fri May 21 19:25:22 UTC 2021


On Friday, 14 May 2021 at 20:58:57 UTC, Dennis wrote:
> ```D
> void main() {
>     int x = 3;
>     string name = x switch {
>         0 => "zero",
>         1 => "one",
>         2 => "two",
>     };
> }
> ```

This particular example can be emulated with this template:

```D
template mapSwitch(alias map)
{
	import std.traits;
	alias T = KeyType!(typeof(map));
	auto mapSwitch(T value)
	{
		switch (value) {
			static foreach (key; map.keys) {
				case key: return map[key];
			}
             default: assert(0);
		}
	}
}

void main() {
	int x = 2;
	string name = x.mapSwitch!([
		0 : `zero`,
		1 : `one`,
		2 : `two`,
	]);
}
```

Both the keys and the values must be known at compile time 
though. We can’t go around this by using lambdas because D 
doesn’t support passing function pointers as template parameters.


More information about the Digitalmars-d mailing list