Functions

Defer in Go

Deferred statements are statements executed prior to the return of a function or method.


Syntax
//any standard function or method
func functionName(paramName returnType) (returnVar returnType) {
    defer //some statement
    //other statements
    return //defer statement happens now
}

Notes

A defer statement occurs when a function returns, the end of the function is reached, or there is a panic.

If there are multiple deferred statements, the statements are executed in LIFO order.

This behavior is similar to callback functions in other languages.


Example
package main

import "fmt"

func countToTen() {
    i := 0
    defer fmt.Println("We have officially counted to 10.")
    for i <= 10 {
        fmt.Println(i)
    }
    //defer statement calls now
}

< Interfaces   |   Print >

© 2019 SyntaxDB. All Rights Reserved.