-
-
Notifications
You must be signed in to change notification settings - Fork 5.7k
Description
This is a problem I have in Query.jl: I sometimes want to iterate things where I am acquiring some resource in the start method that needs to be explicitly freed later on. For example I might open a file in the start method, and at some point I'd like to close it again. I could close it in the last call to the done function, but I can't be sure that it will ever be called, so that is really kind of sloppy.
One solution might be that a normal for loop gets lowered to something like this:
s = start(source)
try
while !done(source, s)
v, s = next(source, s)
# Loop body
end
finally
dispose(source, s)
endWith a default implementation of dispose:
@inline dispose(a,b) = nothingAnd then I could add a method to dispose for my type that closes say a file that I opened in start.
That design would probably only work if the compiler was able to detect cases where the whole try...finalize block did nothing (i.e. where the finally block didn't do anything) and then was able to remove the whole try...finally construct. I assume otherwise it would cause too much of a performance problem.
In any case, even if my idea here doesn't work, it would be good to have some resource management story for iterators.