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.


Comments are closed