"Lazy" initialization of structs

Stanislav Blinov via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Jun 1 05:15:44 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;
> }
> ```

It's not really the same, the structs will have a different type: 
in the first case, it'd be modulename.error.Error, while in the 
second case it's just modulename.Error. Furthermore, if Error 
declared inside the function had methods, it'd become a `nested` 
struct, which carries a context pointer.

> 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.

No, nothing happens at run time, the type is known statically, it 
is inferred from the `return` statement in that function: 
https://dlang.org/spec/function.html#auto-functions.
If you omit the type or specify 'auto', the compiler will look at 
your `return`s (if any) and try to infer the type from them. If 
they clash (i.e. you're trying to return different types from the 
same function), it's a compile-time error. Otherwise, it's 
whatever type is being returned.


More information about the Digitalmars-d-learn mailing list