Equivalent to Python with Statement
Daniel Kozak
kozzi11 at gmail.com
Tue Feb 27 20:29:21 UTC 2018
yes, for classes you can use scoped:
import std.stdio;
import std.typecons : scoped;
class A
{
void saySomething()
{
writeln("Hi from A");
}
~this()
{
writeln("Destruct A");
}
}
void main()
{
with(scoped!A())
{
saySomething();
writeln("something");
}
writeln("Hello D");
}
On Tue, Feb 27, 2018 at 5:25 PM, Jonathan via Digitalmars-d-learn <
digitalmars-d-learn at puremagic.com> wrote:
> 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.
>>
>
> Oh really, cool.
>
> Is this just because the scope of the file variable will end and thus its
> `~this`?
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20180227/3ed0cb9c/attachment-0001.html>
More information about the Digitalmars-d-learn
mailing list