Equivalent to Python with Statement

Seb seb at wilzba.ch
Wed Feb 28 00:02:30 UTC 2018


On Tuesday, 27 February 2018 at 16:18:43 UTC, Stefan Koch wrote:
> On Tuesday, 27 February 2018 at 16:17:20 UTC, Jonathan wrote:
>> I know Python's `with` statement can be used to have an 
>> automatic close action:
>> ```
>>     with open("x.txt") as file:
>>         #do something with file
>>     #`file.close()` called automatically
>> ```
>>
>> I know D's `with` statement does something different but is 
>> there some sort of equivalent?
>
> In this case with(File("bla"))
> will do the same.

FWIW std.stdio.File is refcounted and will be automatically 
closed at the end of the scope. So typically you don't even need 
`with` ;-)
@Jonathan: have a look at these two examples to see what DMD does 
under the hood:


https://run.dlang.io/is/89NBxI
https://run.dlang.io/is/eXC7ZV


More information about the Digitalmars-d-learn mailing list