How would you create this construct?

Mike Parker aldacron at gmail.com
Fri Mar 30 03:14:42 UTC 2018


On Friday, 30 March 2018 at 02:30:01 UTC, Chris Katko wrote:
>
> What I'm trying to do is through this experimental API, is both 
> eliminate the user needing to call a clean-up function 
> explicitly, and, make the "right way" to use the API 
> basically... the only way... to use it.
>
> The way I have written above, there is no way for you to leave 
> my_function() without it automatically calling the cleaning up 
> call. Even if you did a nested version, it would still work!
>
> At first glance, I could do:
>
>     start_draw_calls( {lambda containing all my code} )
>
> But that's not quite as pretty and you're forcing all code to 
> be inside a lambda which... I'm not sure if that has hidden 
> implications / gotchas for code.

Something like this?

=============
import std.stdio;

auto startFoo(int x) {
     struct DO {
         int n;
         this(int n) {
             this.n = n;
         }
         ~this() {
             import std.stdio; writeln("Finished: ", n);
         }
     }
     return DO(x);
}

void main() {
     with(startFoo(10)) {
         writeln("Doing 1");
         writeln("Doing 2");
     }
     writeln("That's all folks");
}
==============

The with statement isn't necessary of course, but I think it's a 
clean way to narrow the scope.

And I'd consider not using "start" in the name if you go this 
route, as it doesn't indicate that there's a return value and it 
would be easy to forget when not using the with statement. 
Perhaps something like "getDrawStarter".


More information about the Digitalmars-d-learn mailing list