Join David Gassner for an in-depth discussion in this video Deferring function calls, part of Up and Running with Go.
- Go's "defer" statement does exactly what it says.…It defers execution of a block of code…until everything else in the current function is finished.…In this file named "defer.go",…I'll start in the main function.…I'll add two lines that output a statement to the console.…The first will say, "Close the file!",…and the second will say, "Open the file!".…Now, I'll open my command prompt, and I'll run that code.…
I see "Close the file!" and then "Open the file!".…Now, I'll come back to the code,…and I'll add the key word "defer"…before the first statement.…I'll save and run that…and now I've reversed the order of execution.…I've said wait until everything else is finished…within this current function, then do this statement.…Each time you call the "defer" statement,…it adds an instruction to a stack,…and when the deferred statements are executed,…they're handled in last in, first out order, known as LIFO.…
Here's a demonstration.…I'm going to defer four statements.…I'll make a copy of this line of code and paste it in,…
- Installing Go tools
- Creating and compiling a Go workspace
- Exploring variables, constants, and types
- Storing ordered and unordered values
- Grouping related values in structs
- Programming conditional logic and loops
- Defining and calling functions
- Handling errors
- Working with files
- Creating a simple HTTP server
Skill Level Beginner
1. Getting Started
2. Essential Go Skills
3. Managing Simple Values
4. Managing Complex Types and Collections
5. Managing Program Flow
6. Structuring Go Code
7. Working with Files and the Web
Next steps2m 26s
- Mark as unwatched
- Mark all as unwatched
Are you sure you want to mark all the videos in this course as unwatched?
This will not affect your course history, your reports, or your certificates of completion for this course.Cancel
Take notes with your new membership!
Type in the entry box, then click Enter to save your note.
1:30Press on any video thumbnail to jump immediately to the timecode shown.
Notes are saved with you account but can also be exported as plain text, MS Word, PDF, Google Doc, or Evernote.