Saturday, May 18, 2024
HomeGolangTurn into a Golang Professional with 10 “Defer” Methods

Turn into a Golang Professional with 10 “Defer” Methods


Go’s defer key phrase is a robust device that permits you to specify a perform name to be executed later, normally after the encircling perform has returned. Though it might seem to be a easy idea, the defer key phrase can be utilized in a number of superior methods to enhance the effectivity and reliability of your Go code.

This put up will discover ten superior tips for utilizing delay in Go. From canceling occasions and releasing sources to printing the time a perform makes use of and recovering from panics, these methods will make it easier to take your Go expertise to the following stage. Whether or not you’re a newbie who desires to study extra about defer, or an skilled developer seeking to develop their data, this put up has one thing for you.

  1. Defer a perform name to execute after the encircling perform returns:
func major() {
defer fmt.Println("This can be printed after major returns")
}

2. Defer a perform name to execute within the reverse order they have been deferred:

func major() {
defer fmt.Println("This can be printed final")
defer fmt.Println("This can be printed second")
defer fmt.Println("This can be printed first")
}

3. Defer a perform name to execute even when a panic happens:

func major() {
defer func() {
if r := recuperate(); r != nil {
fmt.Println("Recovered from panic:", r)
}
}()

// This can trigger a panic
a := []int{1, 2, 3}
fmt.Println(a[3])
}

4. Defer a perform name to shut a file:

func major() {
file, err := os.Open("take a look at.txt")
if err != nil {
fmt.Println(err)
return
}
defer file.Shut()

// Do one thing with the file
}

5. Defer a perform name to unlock a mutex:

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments