Discussion Thread: DIP 1030--Named Arguments--Final Review

Jacob Carlborg doob at me.com
Sun May 17 13:10:37 UTC 2020


On 2020-05-15 21:56, Jonathan M Davis wrote:

> I have _never_ used the struct initialization syntax, and I'm not sure that
> I've ever actually seen it used in any code that I've worked on. In my
> experience, it's also usually the case that structs aren't POD types and
> don't expose their members

I guess it depends on what kind of code you write. It's super useful 
when implementing or using web APIs that use JSON. When doing that I 
have one function per API endpoint, one struct for the request and one 
for the response. For those cases it's only POD structs with all members 
being public.

Just the other day I had to interface with the Datadog API. One of the 
API endpoints expects a JSON body with the following attributes:

struct Request
{
     static struct Time
     {
         string from;
         string timezone = "UTC";
         string to;
     }

     string index = "main";
     int limit;
     string query;
     string sort = "asc";
     string startAt;
     Time time;
}

The only attributes that are required are "query" and "time". With the 
struct initialization syntax it looks very nice:

const Request request = {
     query: "foobar",
     time: {
         from: "now-10s",
         to: "now"
     }
};

Without the above syntax I would need to either use the constructor 
syntax, which makes it very difficult to understand which attributes the 
values belong to. Or using regular field assignment, but then the 
variable cannot be const.

Request request; // cannot be const
request.query = "foobar";
request.time.from = "now-10s";
request.time.to = "now";

The above example could use the `with` statement to shorten the code a bit.

Then just serialize the struct to JSON and pass as the body of the HTTP 
request.

-- 
/Jacob Carlborg


More information about the Digitalmars-d mailing list