View source code
Display the source code in std/sumtype.d from which thispage was generated on github.
Report a bug
If you spot a problem with this page, click here to create aBugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page.Requires a signed-in GitHub account. This works well for small changes.If you'd like to make larger changes you may want to consider usinglocal clone.

Template std.sumtype.tryGet

Attempt to access a SumType's value.

template tryGet(T);

If the SumType does not contain a value of the specified type, an exception is thrown.

Contained Functions

NameDescription
tryGet The actual tryGet function.

Parameters

NameDescription
T the type of the value being accessed.

Example

Basic usage

SumType!(string, double) example = "hello";

writeln(example.tryGet!string); // "hello"

double result = double.nan;
try
    result = example.tryGet!double;
catch (MatchException e)
    result = 0;

// Exception was thrown
writeln(result); // 0

Example

With type qualifiers

import std.exception : assertThrown;

const(SumType!(string, double)) example = "const";

// Qualifier mismatch; throws exception
assertThrown!MatchException(example.tryGet!string);
// Qualifier matches; no exception
writeln(example.tryGet!(const(string))); // "const"
}

/// As a predicate
version (D_BetterC) {

Example

As a predicate

import std.algorithm.iteration : map, sum;
import std.functional : pipe;
import std.exception : assertThrown;

alias Example = SumType!(string, double);

auto arr1 = [Example(0), Example(1), Example(2)];
auto arr2 = [Example("foo"), Example("bar"), Example("baz")];

alias trySum = pipe!(map!(tryGet!double), sum);

writeln(trySum(arr1)); // 0 + 1 + 2
assertThrown!MatchException(trySum(arr2));

Authors

Paul Backus

License

Boost License 1.0