Go Basics – Defer

Actions deferred till just before the Function ends

In the Go language there is a concept of deferring an action till later.

As far as I can tell, the usefulness of this is to allow for the code to be more readable.   In Todd McLeod’s course on Go, he offers an example of this used in an application he wrote. In the app a file is opened, some actions are done to the opened file (such as writing content to it) and then the file is closed.  Instead of having the close at the bottom of the function, he has the close call under the open call.


ipfile, err := os.Open(“ipaddresses.txt”)

defer ipfile.Close()

In the above example, the close is near the call to open the file.  The work done on the file is below the defer action.  Before the function closes, it runs the defer actions

As far as I know… this helps in readability (i.e. we put the open and close actions together), but has no real functionality impact as this could easily have been done using the close call at the end of the function.

What do you think?

0 points
Upvote Downvote

Total votes: 0

Upvotes: 0

Upvotes percentage: 0.000000%

Downvotes: 0

Downvotes percentage: 0.000000%

Written by Admin

I work for a Telecom company writing and testing software. My passion for writing code is expressed through this blog. It's my hope that it gives hope to any and all who are self-taught.

Go – Variadic Functions

Port Scanner written in Go