Special functions

  • Package init func
  • panic
  • defer
  • recover









init

Used to run code that runs before the main function.

All init functions across all packages are executed.










panic

This is an interruption. It will terminate the program, if not handled.










defer

It defers the execution of "something" until the end of the function.

Last in, first out.










It works with panic() and recover().










recover

It is used to recover from a panic.


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

    functionThatCanPanic()
}

func functionThatCanPanic() {
    panic("A problem happened!")
}

Output:

Recovered from panic: A problem happened!









Error handling

We do not have exceptions in Go.










This is the typical design pattern when dealing with errors (~kind of pseudocode):

func readFile(file string) (string, err) {
    // attempt to read the file and set the 'ok' boolean
    if ok {
        return data, nil
    } else {
        return "", errorDetails
    }
}

func main() {
    data, err := readFile("file.txt")
}