What about introducing « defer » (as in Golang)?

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.

E.g. https://crystal-lang.org/api/latest/File.html#open(filename:Path|String,mode="r",perm=DEFAULT_CREATE_PERMISSIONS,encoding=nil,invalid=nil,&)-class-method.

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.

3 Likes

I see, it’s like the « with » construct in Python.

Brilliant.

Problem solved.

1 Like

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

4 Likes

Yes it looks like a very close concept.

Thank you!

1 Like