goroutine的Return与Goexit对比

I did some digging, but didn't really find anything satisfactory, so I'm asking: are their any best practices or pros/cons for using return vs. runtime.Goexit for exiting a goroutine? So far, the only thing I came across in some testing is that if you're using waitgroups, it may not call the Done function.

Specific to the waitgroups (if interested): in some quick testing in a codebase I have, I create an anonymous function that executes as a goroutine to test a method that's supposed to run within a goroutine. I tried to use defer to have it call wg.Done() when the function called runtime.Goexit, but it didn't work. Not sure if this is intended or a bug.

Code example:

go func() {
    wg.Add(1)
    defer wg.Done()
    // Function goes here...
}()

You should rarely ever need to use runtime.Goexit. It's used to terminate the current goroutine, when you can't return from the call site, e.g. when you are in a function call within the goroutine. In the std library, the testing package uses it in functions like FailNow and SkipNow to immediately end the current test. In general, you should return normally from your goroutines to keep the code clear, and prevent unexpected behavior.

The problem in your example is that you need to call wg.Add before you start the goroutine, otherwise you could reach the Wait call before the wg.Add calls have been executed.

wg.Add(1)
go func() {
    defer wg.Done()
    // Function goes here...
}()