Does D have any construct like Python's with keyword?

Adam D. Ruppe via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Aug 26 18:11:38 PDT 2016


On Saturday, 27 August 2016 at 00:04:47 UTC, pineapple wrote:
>     context(auto file = File("some_file.txt")){
>         file.write();
>     }

You don't need to do anything special for that in D, structs are 
destructed automatically. Plain

auto file = File("some_file.txt");
file.write();


will automatically close file when it goes out of scope. If you 
want it to go out of scope earlier, you can:

{
auto file = File("some_file.txt");
file.write();
}

the curly braces around it will make a new scope, so the 
destructor, which closes the file, will be called at the }.


More information about the Digitalmars-d-learn mailing list