What about introducing « defer » (as in Golang)?
… for closing file handles etc. (to minimise chances of forgetting to close files?)
What about introducing « defer » (as in Golang)?
… for closing file handles etc. (to minimise chances of forgetting to close files?)
In crystal the equivalent would be blocks: Blocks and Procs - Crystal.
File.open("path/to/file", "w") do |file|
file.puts "foo"
end
Is equivalent to:
file = File.new "path/to/file", "w"
file.puts "foo"
file.close
as the method closes the file after yielding: crystal/file.cr at e7b46c40739902db70a2dceebd09caf1a7c70553 · crystal-lang/crystal · GitHub.
EDIT: This can probably be moved to Help & Support - The Crystal Programming Language Forum.
I see, it’s like the « with » construct in Python.
Brilliant.
Problem solved.
Unless there is an error.
In Crystal, the equivalent is ensure
. Same effect as defer
:
def test
puts "Hello"
ensure
puts "Always called!"
end
https://crystal-lang.org/reference/syntax_and_semantics/exception_handling.html#ensure
Yes it looks like a very close concept.
Thank you!