"Lazy" initialization of structs

Nicholas Wilson via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Jun 1 05:13:48 PDT 2017


On Thursday, 1 June 2017 at 12:04:05 UTC, Daniel Tan Fook Hao 
wrote:
> Somehow this code works for me:
>
> ```D
> auto error (int status, string description){
>     struct Error {
>         int status;
>         string description;
>     }
>     Error err = {
>         status,
>         description
>     };
>     return err.serializeToJson;
> }
> ```
>
> which is supposed to be the same as
>
> ```D
> struct Error {
>     int status;
>     string description;
> }
> auto error (int status, string description){
>     Error err = {
>         status,
>         description
>     };
>     return err.serializeToJson;
> }
> ```
>
> If I'm reading this right, in the former, the struct is created 
> when the function is called in run-time, and the type is then 
> inferred after that? I don't really understand the behavior 
> behind this.

They are both functionally equivalent but the Error struct is 
visible at module scope in the first example, but only visible 
(nameable) within the function for the second example.

The return type of both is whatever `serializeToJson` returns, a 
Json object.

You can also return the struct directly and the same visibly 
rules apply. In that use the returned type is what is known as a 
Voldemort type( https://wiki.dlang.org/Voldemort_types).




More information about the Digitalmars-d-learn mailing list