The runtime.Goexit()
function is used to forcefully exit the current Goroutine, not the entire program. When it is called, the Goroutine immediately stops executing and the program continues running with any other Goroutines that have been created.
Here's an example of how to use runtime.Goexit()
to exit a Goroutine:
package main
import (
"fmt"
"runtime"
)
func goroutineFunc() {
defer fmt.Println("This line will not be executed.")
fmt.Println("Goroutine is running.")
// Forcefully exit the Goroutine
runtime.Goexit()
}
func main() {
fmt.Println("Main Goroutine is running.")
go goroutineFunc()
// Keep the main Goroutine running indefinitely
for {
}
}
In this example, the goroutineFunc()
is a separate Goroutine launched by the go
keyword. Inside this Goroutine, the runtime.Goexit()
function is called, which forcibly exits this Goroutine.
However, the main
Goroutine will continue running indefinitely since it contains an infinite loop (for {}
). Therefore, the program as a whole does not exit.