I'm having some issues understanding the difference between func() go func() defer func()
I have a program
package main
import "fmt"
func main() {
say := func(args ...string) {
fmt.Println(args)
}
func(msg string) {
say(msg)
}("func")
defer func(msg string) {
say(msg)
}("defer func")
go func(msg string) {
say(msg)
}("go func")
}
and it outputs [func] [defer func]
What does 'go func' do that causes it not to output here?
What's the difference between defer func and func? Is it similar to JS where defer will not block, where func will?
评论:
JHunz:
Growlizing:func is executed immediately. Nothing particularly to note.
defer func executes the function after everything else in the function it is called in finishes, directly before it returns. If you put the deferred call above the regular call, it would still print last.
go func executes the function in a separate goroutine. It's likely that the reason you are not seeing it print anything is that the program is finishing and exiting prior to the print command from that call being executed. If you want to guarantee that goroutines finish, you should look up WaitGroups in the sync package.
danhardman:I am not sure about this, but I don't think defer is guaranteed to execute if deferred in main. Deferred functions are not run if os.Exit() is called.
syzo_:
defer
gets ran once the surrounding function ends.
go ...
creates a go routine (like a new thread but not a thread, a better thing) to complete the function.What I suspect is happening is once
go func
is called,main()
returns and thedefer func
gets called and the application exits before the go routine has finished.Try add
time.Sleep(3 * time.Second)
to make the program wait before exiting.
stuartcarnie:Noob question on my phone right now, if you have multiple defers, what order do they get called in at the end? Either queue or stack, id imagine
okashi-seattle:Per the spec, it is a stack
Instead, deferred functions are invoked immediately before the surrounding function returns, in the reverse order they were deferred.
Also worthwhile adding that even though the function call happens at the end after the return, the arguments passed to the defer function are evaluated immediately.

为什么 洋人会问问题,而且提问题质量,而且解答的水准,都比我们高一大截子呢?