Defer - Go Lang Practical Programming Tutorial p.20

sentdex · Beginner ·🛠️ AI Tools & Apps ·8y ago

Key Takeaways

The video discusses the defer statement in Go programming language, its use in handling errors and ensuring code execution, and introduces the concept of panic and recover.

Full Transcript

what's going on everybody welcome to part 20 of the go language programming tutorial series in this tutorial what we're going to be talking about is the defer statement in ingo so what we're talking about in the last tutorial was hey we're using this kind of weight group and all that and it's really cool but what if we run into something that causes this function to error and we we don't actually get to tell the weight group hey we're done well then we're gonna have a problem we're gonna be waiting all right and we don't want that so this isn't a problem that you're gonna come across with just doing go routines and weight groups for example when you want to close connections when you're done or close files or whatever if you hit an error before you get to the clothes you're never gonna actually run that operation so in go they have the defer statement so the idea of defer is it'll be evaluated whenever it gets hit but actually the defer statement won't run whatever's being deferred until the surrounding function either completes or panics out so if the if once it's been evaluated if that function does happen to panic out all of the deferred functions will run so if it's an error or if it doesn't hit an error basically whenever that function is all set and done it's gonna go ahead and run whatever you decided to defer so to exemplify this I'm gonna go ahead and clear clean up here we'll come back to this you can I would recommend you save this because I'm just going to copy and paste it over when we return back to this but I just want to use a more simple example for now so let's say we've got a func we'll call it foo and foo basically just does a format dot print line and you know this is a function that does some stuff who knows right and then funk mein can run Fuu okay so if we wanted to we could we could say okay while this function is doing some stuff we want to make sure when it's done doing some stuff we want to make sure it runs format dot print line done so this is gonna be evaluated immediately but it's only gonna run when the rest of the foo function is done so let me pull this up and let's run that real quick and we can see yeah it says doing some stuff who knows what and then it's done running now what if we added another like what if we threw in another defer statement so we should so let's do [Music] are we done so the way to first statements work is in a first in last out order I'm not really sure why they why it's that way but basically that also means last in will be first out so what we're gonna see when we run this is doing some stuff are we done and then done so for just to show that right sure enough that's that's how it ran so we could also exemplify that with like a for loop or something like that so for example we could we could say for I colon equals 0 Wow I less than 5 we could just say defer format print line high so save that run it and sure enough it basically counts down right so getting back to our main example I'm just gonna kind of copy and paste it over copy paste so this is our original example where we kind of came into this so this one it works and it waits so just to show right it just runs those two go routines waits for them to finish but if wait group done never runs we're in trouble so what we could say is rather than running WG gun down here we'll just cut that and then we defer wait group done to the top so then we can save that and and now we can rerun function or the program and now we've got hey there hey there hey there okay so that is how we can defer things and why we might want to defer things and if we're going to be talking about the defer statement we might as well also talk about panic and recover in the go programming language so while we can use defer to make sure something happens we can also use defer to recover after a panic has occurred so so you could defer some sort of function that's gonna handle for whatever the error was that we might have actually hid that way your program doesn't stop running or at least it doesn't have to you could let it stop running but you don't have to do that anyway in the next tutorial that's we're gonna be talking about we should have no problem covering both panic and recover in the next tutorials so panic is a way that we can say hey we've hit an error based on some sort of condition so we can panic out but also like I was saying defer doesn't necessarily only run if the function successful defer will also all the deferred statements are gonna run if the function also panics out so if the surrounding function panics out all the deferred functions will also run so then within within those deferred functions we can recover from panics so anyways that's what we're going to talk about in the next tutorial if you have questions comments concerns whatever feel free to Livan below otherwise I'll see you in the next tutorial

Original Description

Welcome to part 20 of the Go programming tutorial, where we will be introducing the defer statement and its use in Go. The idea of the defer statement is to put off (defer) the execution of something until the surrounding function is done. Text tutorials and sample code: https://pythonprogramming.net/go/ https://twitter.com/sentdex https://www.facebook.com/pythonprogramming.net/ https://plus.google.com/+sentdex
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from sentdex · sentdex · 0 of 60

← Previous Next →
1 Matplotlib Python Tutorial Part 1: Basics and your first Graph!
Matplotlib Python Tutorial Part 1: Basics and your first Graph!
sentdex
2 Python Encryption Tutorial with PyCrypto
Python Encryption Tutorial with PyCrypto
sentdex
3 Python's Logging Function
Python's Logging Function
sentdex
4 wxPython Tutorials 1: Making Windows GUIs with Python : Installing + 1st window!
wxPython Tutorials 1: Making Windows GUIs with Python : Installing + 1st window!
sentdex
5 wxPython Tutorials 2: Making Windows GUIs with Python: Customizing Window Parameters
wxPython Tutorials 2: Making Windows GUIs with Python: Customizing Window Parameters
sentdex
6 wxPython Programming Tutorial 3: Menu Bar and Menu Button
wxPython Programming Tutorial 3: Menu Bar and Menu Button
sentdex
7 wxPython Programming Tutorial 4: Panels
wxPython Programming Tutorial 4: Panels
sentdex
8 wxPython Programming Tutorial 5: User Input Saved To Variables
wxPython Programming Tutorial 5: User Input Saved To Variables
sentdex
9 wxPython Programming Tutorial 6: Multiple Choice Input
wxPython Programming Tutorial 6: Multiple Choice Input
sentdex
10 wxPython Programming Tutorial 7: Adding Static Text and Colors
wxPython Programming Tutorial 7: Adding Static Text and Colors
sentdex
11 wxPython Programming Tutorial 8: Custom Button Images
wxPython Programming Tutorial 8: Custom Button Images
sentdex
12 wxPython Programming Tutorial 9: Tool Bar Items and Sub Menus!
wxPython Programming Tutorial 9: Tool Bar Items and Sub Menus!
sentdex
13 Basic PHP Tutorial 13: Multi-dimensional Array
Basic PHP Tutorial 13: Multi-dimensional Array
sentdex
14 Basic PHP Tutorial 15: Functions and Global Variables
Basic PHP Tutorial 15: Functions and Global Variables
sentdex
15 Basic PHP Tutorial 12: Associative Array
Basic PHP Tutorial 12: Associative Array
sentdex
16 Basic PHP Tutorial 14: Foreach loop
Basic PHP Tutorial 14: Foreach loop
sentdex
17 Basic PHP Tutorial 16: Include and Require
Basic PHP Tutorial 16: Include and Require
sentdex
18 Basic PHP Tutorial 7: Assignment, comparison and Logical operators
Basic PHP Tutorial 7: Assignment, comparison and Logical operators
sentdex
19 Basic PHP Tutorial 4: Variables and Comments
Basic PHP Tutorial 4: Variables and Comments
sentdex
20 Basic PHP Tutorial 11: Arrays part 1, basic array
Basic PHP Tutorial 11: Arrays part 1, basic array
sentdex
21 Basic PHP Tutorial 6: If else and else if conditionals cont'd
Basic PHP Tutorial 6: If else and else if conditionals cont'd
sentdex
22 Basic PHP Tutorial 1: Intro to PHP
Basic PHP Tutorial 1: Intro to PHP
sentdex
23 Basic PHP Tutorial 3: HTML with PHP
Basic PHP Tutorial 3: HTML with PHP
sentdex
24 Basic PHP Tutorial 9: While Loop
Basic PHP Tutorial 9: While Loop
sentdex
25 Basic PHP Tutorial 10: Switch Statement
Basic PHP Tutorial 10: Switch Statement
sentdex
26 Basic PHP Tutorial 2: Print and Echo
Basic PHP Tutorial 2: Print and Echo
sentdex
27 Basic PHP Tutorial 5: If else and else if conditional statements
Basic PHP Tutorial 5: If else and else if conditional statements
sentdex
28 Basic PHP Tutorial 8: Arithmatic Operators: Doing math with php
Basic PHP Tutorial 8: Arithmatic Operators: Doing math with php
sentdex
29 Basic PHP Tutorial 17: User Input Form Example / String Manipulation
Basic PHP Tutorial 17: User Input Form Example / String Manipulation
sentdex
30 Basic PHP Tutorial 18: HTML Entities and forms cont'd
Basic PHP Tutorial 18: HTML Entities and forms cont'd
sentdex
31 Basic PHP Tutorial 19: Finding words in strings
Basic PHP Tutorial 19: Finding words in strings
sentdex
32 Basic PHP Programming Tutorial 20: Saving to a File / writing and appending
Basic PHP Programming Tutorial 20: Saving to a File / writing and appending
sentdex
33 Basic PHP Programming Tutorial 22: Hashing part 2: salting
Basic PHP Programming Tutorial 22: Hashing part 2: salting
sentdex
34 Basic PHP Programming Tutorial 23: Variables in Strings and tokenizing
Basic PHP Programming Tutorial 23: Variables in Strings and tokenizing
sentdex
35 Basic PHP Programming Tutorial 21: MD5 Hashing For Security
Basic PHP Programming Tutorial 21: MD5 Hashing For Security
sentdex
36 Basic PHP Programming Tutorial 24: String similarity
Basic PHP Programming Tutorial 24: String similarity
sentdex
37 Basic PHP Programming Tutorial 25: Time and Time stamps
Basic PHP Programming Tutorial 25: Time and Time stamps
sentdex
38 Basic PHP Programming Tutorial 26: Die and Exit
Basic PHP Programming Tutorial 26: Die and Exit
sentdex
39 Basic PHP Programming Tutorial 27: MySQL Databases Part 1
Basic PHP Programming Tutorial 27: MySQL Databases Part 1
sentdex
40 Basic PHP Programming Tutorial 28: MySQL Database Part 2: Reading From Database
Basic PHP Programming Tutorial 28: MySQL Database Part 2: Reading From Database
sentdex
41 Basic PHP Programming Tutorial 29: MySQL Database Part 3: Inputting Data
Basic PHP Programming Tutorial 29: MySQL Database Part 3: Inputting Data
sentdex
42 Basic PHP Programming Tutorial 30: MySQL database in Use
Basic PHP Programming Tutorial 30: MySQL database in Use
sentdex
43 Django Tutorial Web Development with Python Part 1: Installing Django
Django Tutorial Web Development with Python Part 1: Installing Django
sentdex
44 Python Tutorial: File Deletion and Folder Deletion / directory deletion
Python Tutorial: File Deletion and Folder Deletion / directory deletion
sentdex
45 Python Tutorial: How to Rename Files and Move Files with Python
Python Tutorial: How to Rename Files and Move Files with Python
sentdex
46 3D Graphs in Matplotlib for Python: Basic 3D Line
3D Graphs in Matplotlib for Python: Basic 3D Line
sentdex
47 3D Plotting in Matplotlib for Python: 3D Scatter Plot
3D Plotting in Matplotlib for Python: 3D Scatter Plot
sentdex
48 3D Charts in Matplotlib for Python: Multiple datasets scatter plot
3D Charts in Matplotlib for Python: Multiple datasets scatter plot
sentdex
49 Sikuli Tutorial 1: Visually programming in python!
Sikuli Tutorial 1: Visually programming in python!
sentdex
50 Sikuli Tutorial 2: Program visually in python!
Sikuli Tutorial 2: Program visually in python!
sentdex
51 Sikuli Tutorial 3: Program visually in python!
Sikuli Tutorial 3: Program visually in python!
sentdex
52 3D Bar Charts in Python and Matplotlib
3D Bar Charts in Python and Matplotlib
sentdex
53 3D Plane wire frame Graph Chart in Python
3D Plane wire frame Graph Chart in Python
sentdex
54 Raspberry Pi Part 1 Introduction
Raspberry Pi Part 1 Introduction
sentdex
55 Raspberry Pi Part 8: First Download and Update! (Firmware)
Raspberry Pi Part 8: First Download and Update! (Firmware)
sentdex
56 Raspberry Pi Part 10: How to set up a Linux Web Server on your Pi
Raspberry Pi Part 10: How to set up a Linux Web Server on your Pi
sentdex
57 Raspberry Pi Part 11: Remote Desktop
Raspberry Pi Part 11: Remote Desktop
sentdex
58 Twitter Analysis: How to rank a user's influence
Twitter Analysis: How to rank a user's influence
sentdex
59 GPIO Tutorial for Pi Part 2 - Programming the GPIO
GPIO Tutorial for Pi Part 2 - Programming the GPIO
sentdex
60 GPIO Tutorial for Raspberry Pi Part 1 - Setting up
GPIO Tutorial for Raspberry Pi Part 1 - Setting up
sentdex

The defer statement in Go is used to delay the execution of a function until the surrounding function is done. It is useful in handling errors and ensuring code execution. The video also introduces panic and recover concepts.

Key Takeaways
  1. Use the defer statement to delay function execution
  2. Handle errors using defer
  3. Apply concurrency concepts using goroutines and weight groups
  4. Use panic and recover to handle errors
💡 The defer statement in Go is a powerful tool for handling errors and ensuring code execution, and can be used in conjunction with panic and recover to create robust and reliable code.

Related Reads

📰
How I Built a Free Online Image & PDF Processing Platform with Vue 3 + FastAPI
Learn how to build a free online image and PDF processing platform using Vue 3 and FastAPI, and discover the benefits of combining these technologies for efficient file processing
Dev.to · IAMUU
📰
I Built a Free AI-Powered YouTube SEO Toolkit With Zero Budget. Here’s What Actually Happened.
Learn how a solo dev built a free AI-powered YouTube SEO toolkit with zero budget and the lessons they learned from the experience
Medium · Startup
📰
How to Create a Second Version of Yourself Inside Obsidian Using AI (Step-by-Step Guide)
Learn to create a second version of yourself inside Obsidian using AI with a step-by-step guide
Medium · ChatGPT
📰
How to prepare for Spain civil service TIC exam using AI in 2026
Learn how to prepare for the Spain civil service TIC exam using AI in 2026, boosting your chances of success with technology-driven study techniques
Dev.to · David García
Up next
I Asked Gemini to Build a Dashboard... I Didn't Expect This
Patech
Watch →