<p>I'm having some issues understanding the difference between
func()
go func()
defer func()</p>
<p>I have a program</p>
<pre><code>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")
}
</code></pre>
<p>and it outputs
[func]
[defer func]</p>
<p>What does 'go func' do that causes it not to output here?</p>
<p>What's the difference between defer func and func? Is it similar to JS where defer will not block, where func will?</p>
<hr/>**评论:**<br/><br/>JHunz: <pre><p>func is executed immediately. Nothing particularly to note. </p>
<p>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. </p>
<p>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.</p></pre>Growlizing: <pre><p>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.</p></pre>danhardman: <pre><p><code>defer</code> gets ran once the surrounding function ends.</p>
<p><code>go ...</code> creates a go routine (like a new thread but not a thread, a better thing) to complete the function.</p>
<p>What I suspect is happening is once <code>go func</code> is called, <code>main()</code> returns and the <code>defer func</code> gets called and the application exits before the go routine has finished.</p>
<p>Try add <code>time.Sleep(3 * time.Second)</code> to make the program wait before exiting.</p></pre>syzo_: <pre><p>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</p></pre>stuartcarnie: <pre><p>Per <a href="https://golang.org/ref/spec#Defer_statements">the spec</a>, it is a stack</p>
<blockquote>
<p>Instead, deferred functions are invoked immediately before the surrounding function returns, in the reverse order they were deferred.</p>
</blockquote></pre>okashi-seattle: <pre><p>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.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传