Skip to content

Commit 3f990a7

Browse files
authored
Merge pull request #10650 from pbackus/sumtype-proc-api
Procedural API for SumType
2 parents 4a91ed7 + 1d3177f commit 3f990a7

File tree

2 files changed

+465
-15
lines changed

2 files changed

+465
-15
lines changed

changelog/sumtype_procedural_api.dd

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
New procedural API for `std.sumtype`
2+
3+
`std.sumtype` has three new convenience functions for querying and retrieving
4+
the value of a `SumType` object.
5+
6+
* `has!T` returns `true` if the `SumType` object has a value of type `T`.
7+
* `get!T` returns the value if its type is `T`, or asserts if it is not.
8+
* `tryGet!T` returns the value if its type is `T`, or throws an exception if it
9+
is not.
10+
11+
These functions make it easier to write code using `SumType` in a procedural
12+
style, as opposed to the functional style encouraged by `match`.
13+
14+
Example:
15+
16+
---
17+
import std.sumtype;
18+
import std.stdio;
19+
20+
SumType!(string, double) example = "hello";
21+
22+
if (example.has!string)
23+
{
24+
writeln("string: ", example.get!string);
25+
}
26+
else if (example.has!double)
27+
{
28+
writeln("double: ", example.get!double);
29+
}
30+
31+
try
32+
{
33+
writeln("double: ", example.tryGet!double);
34+
}
35+
catch (MatchException e)
36+
{
37+
writeln("Couldn't get a double.");
38+
}
39+
---

0 commit comments

Comments
 (0)