feature request: with(var decl) {}

Adam D. Ruppe destructionator at gmail.com
Mon Jul 23 07:37:38 PDT 2012


I was just thinking about porting a javascript function to
D that takes an object of params:

function foo(args) { ... }

foo( { "closeButton" : false, "width" : 200 } );


In D, I figured I'd make args a struct:

struct FooArgs {
    bool closeButton = true; // the default is for it to be there
    int width = 600;
}

void foo(FooArgs args) { ... }


And, of course, this works, but it was leaving a declared
variable around and can be somewhat repetitive. But first
I tried making it look kinda like the JS:

FooArgs args = { closeButton: false };
foo(args);

But, that style struct initializer doesn't respect the default
values. Here, width == 0. No good.


So, then, well, that's OK, I'll just write it out:

FooArgs args;
args.closeButton = false;
foo(args);



There we go, not too bad at all. We can kill some repetition
of "args" with the with() {} statement. Great!

But, what if I have another call later? I don't want that args
sticking around.


FooArgs args;
// ...
foo(args);

BarArgs args; // error, args already declared




No prob, let's scope it! I tried:


with(FooArgs args) {
    closeButton = false;
    foo(args);
}

// can redeclare another args here if you want


But it didn't work. It is with(symbol) or with(expression)
in the spec.



Would it work to also allow with(decl)? It seems to me that
it should be ok... kinda similar to the currently allowed

if(auto a = foo()) { /* use a here */ }


So we're just extending that same idea out to the with statement
too.


More information about the Digitalmars-d mailing list