Senior
What happens if defer is placed outside the goroutine, not inside?
sobes.tech AI
Answer from AI
If defer is placed outside the goroutine, the deferred function will be called when exiting the outer function, not when the goroutine finishes. This means that resources you intended to free inside the goroutine may remain occupied until the outer function completes.
For example:
func main() {
defer fmt.Println("defer in main")
go func() {
defer fmt.Println("defer in goroutine")
fmt.Println("inside goroutine")
}()
time.Sleep(time.Second)
}
If defer is inside the goroutine, it will execute when the goroutine finishes. If defer is declared outside, it will execute when exiting main, regardless of the goroutine.
Therefore, defer should be inside the goroutine if you want to guarantee resource release exactly when that goroutine finishes.