How to initialize immutable variables with an expression that throws an exception to catch?

Ali Çehreli acehreli at yahoo.com
Fri Apr 3 15:43:51 UTC 2020


On 4/2/20 11:56 PM, FeepingCreature wrote:

> The only way I've found is to make fun() return Algebraic!(S, Exception) 
> but that's kind of ugly and bypasses a basic language feature.

How about using a Nullable!(immutable(S)):

import std.typecons;
alias NS = Nullable!(immutable(S));

NS makeS() {
   try {
     return NS(fun());

   } catch (Exception) {
     return NS();
   }
}

struct S { }

S fun() {
   return S();
}

void call(immutable(S) s) {
}

void foo() {
   auto ns = makeS();
   if (!ns.isNull) {
     call(ns.get);
   }
}

void main() {
   foo();
}

Ali


More information about the Digitalmars-d mailing list