How to declare immutable struct outside of try catch and reference it later

Jonathan M Davis newsgroup.d at jmdavisprog.com
Sun Dec 3 07:37:33 UTC 2017


On Sunday, December 03, 2017 05:49:54 Fra Mecca via Digitalmars-d-learn 
wrote:
> I have this code:
>      Configuration conf = void ;
>      try {
>          conf = parse_config("config.sdl");
>      } catch (Exception e) {
>          std.stdio.stderr.writeln("Error reading configuration
> file: ", e.msg);
>          exit(1);
>      }
>
> // other code
> function(value, conf);
> // end
>
> I get:
> source/app.d(18,3): Error: cannot modify struct conf
> Configuration with immutable members
>
> Is there a way to declare conf outside of the try catch block and
> use it later?
> I thought void explicitly avoid inizialization.

It's not possible to delay initialization with const or immutable variables
unless they're member variables (which then have to be initialized in a
constructor before they're used), but you can wrap the try-catch block in a
function or lambda that returns the struct so that the code is separated out
in a way that the variable is then directly initialized.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list