Defer in Golang

defer statement helps to execute program statement or anonymous function at end of the function execution.

Example Program:

package main

import "fmt"

func main() {
    fmt.Println("Start Main")
    testfunction()
    fmt.Println("End Main")
}

func testfunction() {
    /* This defer statement executed end of the function */
    defer fmt.Println("test function finished and exit")

    /* Do the work of funtion */
    var a, b int = 10, 20
    var c int = a + b 
    fmt.Println("Value of Addition", c)
}

Output:

Start Main
Value of Addition 30
test function finished and exit
End Main

One of the use case for defer statement is open a file for writing, next inside the defer mention file close then go for write. once function execution done defer will close the file automatically.

No comments:

Post a Comment