Does D have any construct like Python's with keyword?
pineapple via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Aug 26 17:01:11 PDT 2016
On Friday, 26 August 2016 at 23:30:15 UTC, Cauterite wrote:
> On Friday, 26 August 2016 at 23:28:27 UTC, pineapple wrote:
>> I've grown to very much appreciate how context initialization
>> and teardown can be very conveniently handled using `with` in
>> Python. Is there any clean way to imitate this syntax in D?
>
> Yep, scope guards.
>
> auto p = OpenProcess(...);
> scope(exit) {CloseHandle(p);};
What I had in mind was something more like this, but not quite so
messy-looking. Though after having actually written it out I'm
wondering if it's not better to just keep it looking like this,
or similar, rather than make it part of the language. It's not
_too_ hideous.
import std.stdio;
void context(Context, Dg)(Context context, Dg content){
scope(exit) context.conclude;
content(context);
}
struct File{
this(string path){
writeln("open a file");
}
void write(){
writeln("write some data");
}
void conclude(){
writeln("close the file");
}
}
void main(){
context(File("some_file.txt"), (File file){
file.write();
});
}
More information about the Digitalmars-d-learn
mailing list