It is impossible to interrupt the gorutin outside.
You can set some flag and check it inside the function or pass the channel as a parameter and write the value there when you need to interrupt the function.
But to check that the flag that the channel must the gorutina, which must be stopped. Only she herself can complete her execution.
The exception is os.Exit (...), but then the whole program stops at once, no defer, finalizers, etc. not called.
those.
func f(){ for {} }
you can not stop without the completion of the program entirely.
You can do something like
package main import ( "fmt" "time" ) func main() { flag := false go f(&flag) time.Sleep(time.Second) flag = true time.Sleep(time.Second) fmt.Println(2) } func f(flag *bool) { for { if *flag { fmt.Println(1) return } } }
Or so:
package main import ( "fmt" "time" ) func main() { stop := make(chan bool) go f(stop) time.Sleep(time.Second) stop <- true time.Sleep(time.Second) fmt.Println(2) } func f(stop chan bool) { for { select { case <-stop: fmt.Println(1) return default: // ΠΠ΅ΡΠΊΠ° default Π½ΡΠΆΠ½Π°, ΡΡΠΎΠ±Ρ ΠΏΡΠΈ ΠΎΡΡΡΡΡΡΠ²ΠΈΠΈ ΡΠΎΠΎΠ±ΡΠ΅Π½ΠΈΠΉ Π² chan ΡΠ°Π±ΠΎΡΠ° ΡΡΠ½ΠΊΡΠΈΠΈ ΠΏΡΠΎΠ΄ΠΎΠ»ΠΆΠΈΠ»Π°ΡΡ Π²ΠΌΠ΅ΡΡΠΎ Π±Π»ΠΎΠΊΠΈΡΠΎΠ²ΠΊΠΈ Π½Π° ΠΎΠΆΠΈΠ΄Π°Π½ΠΈΠΈ ΡΠΎΠΎΠ±ΡΠ΅Π½ΠΈΡ } } }