Added toOptional function.
Build and Test Module / build-and-test (push) Successful in 6s Details
Build and Test Module / build-and-test-with-asdf-library (push) Successful in 11s Details

This commit is contained in:
Andrew Lalis 2026-06-15 17:42:38 -04:00
parent 97d996b90c
commit 2d97e36b0c
1 changed files with 20 additions and 0 deletions

View File

@ -147,6 +147,18 @@ auto mapIfPresent(alias fn, T)(Optional!T opt) {
return Optional!U.of(fn(opt.value));
}
/**
* Helper function to get an Optional value for an existing value. Due to D's
* type inference, you can simply write `auto opt = toOptional(x);` to avoid
* having to write out types when constructing optionals.
* Params:
* t = The value to construct an optional from.
* Returns: The optional with the given value.
*/
Optional!T toOptional(T)(T t) {
return Optional!T.of(t);
}
unittest {
Optional!string s = Optional!string.of("hello");
assert(!s.isNull);
@ -208,3 +220,11 @@ unittest {
}
}
}
// Tests for toOptional.
unittest {
int x = 5;
auto optX = x.toOptional;
assert(!optX.isNull);
assert(optX.value == 5);
}