How to initialize immutable variables with an expression that throws an exception to catch?
Steven Schveighoffer
schveiguy at gmail.com
Fri Apr 3 12:49:27 UTC 2020
On 4/3/20 2:56 AM, FeepingCreature wrote:
> Consider the following code:
>
> struct S { }
> ....
> S s = void;
> try
> s = fun();
> catch (Exception)
> return;
> call(s);
>
> Now you change S to be immutable.
>
> How are you supposed to initialize s? You can't assign to it anymore.
>
> Assume that we explicitly don't want to pull the call into the try body,
> for instance because we want exceptions from call to not be caught.
>
> 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.
>
> Maybe D could allow to initialize an immutable variable from the try{}
> body if the catch{} body is statically known to exit by return/throw?
Do it the old-fashioned way -- use casting ;)
S s_val = void;
try
s_val = fun();
catch (Exception)
return;
immutable s = s_val.assumeUnique;
call(s);
It's not as pretty and has a "code-by-assumption" issue. I wish you
could just lambda-initialize this, but the return statement throws a
wrench into that.
-Steve
More information about the Digitalmars-d
mailing list