Skip to content

tour: defer - a short description on a genuine use for defer may be helpful #1673

Description

@benkoshy

Context: https://go.dev/tour/flowcontrol/12

Defer
A defer statement defers the execution of a function until the surrounding function returns.
The deferred call's arguments are evaluated immediately, but the function call is not executed until the surrounding function returns.

A brief explanation of why defering is necessary may be helpful. Because the example given seems contrived:

package main

import "fmt"

func main() {
	defer fmt.Println("world")

	fmt.Println("hello")
}

A tyro may ask: why not the following instead?

fmt.Println("hello")
fmt.Println("world")

i.e. in what scenario would defer be necessary? It seems that in every case I can think of - you could achieve the same outcome by ordering the execution differently.

my 2 cents.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions