Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
benkoshy opened this issue Dec 16, 2024 · 0 comments
Open

Comments

@benkoshy
Copy link

benkoshy commented Dec 16, 2024

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.

@benkoshy benkoshy changed the title tour: defer - a short description on a genuine use for defer case may be helpful tour: defer - a short description on a genuine use for defer may be helpful Dec 16, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant