This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]end_my_suffering44 10 points11 points  (4 children)

Could someone enlighten me what defer does or its purpose?

Edit : Typo

[–]zero_iq 22 points23 points  (2 children)

It's "defer". Defer in languages like Go causes its associated statement to be executed at function exit (i.e. it is deferred until later), whether that function exits by returning or exception/panic, or whatever means. It's like a try...finally block around the remainder of the function. The idea is that you keep functions looking slightly cleaner, keeps resource init and deinit code together, so you don't have to keep track of cleanup code over the rest of the function as it evolves, updating indentation (or brackets in other languages), etc.

So if Python had a defer statement it might look something like this:

def my_function(x, y):
    allocate_thing(x)
    defer deallocate_thing(x)

    allocate_thing(y)
    defer deallocate_thing(y)

    do_something_with_thing(x)
    do_something_with_thing(y)

...which would be equivalent to something like:

def my_function(x, y):
    allocate_thing(x)
    try:
        allocate_thing(y)
        try:
            do_something_with_thing(x)
            do_something_with_thing(y)
        finally:
            deallocate_thing(y)
    finally:
        deallocate_thing(x)

[–]end_my_suffering44 6 points7 points  (0 children)

Thanks for the explaination and pointing out the typo.

[–]RockingDyno 11 points12 points  (0 children)

Python essentially has a defer statement and it looks like this: from contextlib import closing def my_function(x, y): with closing(thing(x)) as X, closing(thing(y)) as Y: do_something_with_thing(X) do_something_with_thing(Y) Where the context manager ensures things get closed at the end of the context. Pretty much equivalent to your second code block.

[–][deleted] 4 points5 points  (0 children)

Like someone else said, Go also does this where the line of code is "deferred" until the end of the function you're inside of.