Last Function

The last call inside a function

  1 package main
  2
  3 import "fmt"
  4
  5 func main() {
  6         defer fmt.Println("exit")
  7         fmt.Println("start")
  8 }
package main

import "fmt"

func main() {
        defer fmt.Println("exit")
        fmt.Println("start")
}
go run main.go
start
exit

In line 6 the

        defer fmt.Println("exit")

is called at the end of the main function.

This is often used for file handling. When you open the file you add an defer close to make sure, the file will be closed at the end of the function.

Source

See the full source on github.

Sources