package mainimport ( "context" "fmt" "time")func main() { ctx := context.Background() c, fn := context.WithCancel(ctx) go doSth(c) time.Sleep(1 * time.Second) fn() time.Sleep(10 * time.Second)}func doSth(ctx context.Context) { fmt.Println("doing") time.Sleep(2 * time.Second) fmt.Println("still doing") select { case <-ctx.Done(): fmt.Println("cancel") return }}輸出:doingstill doingcancel我不知道當(dāng)它獲得的上下文是取消時(shí)如何使這個(gè) doSth 函數(shù)返回。換句話說,我希望這個(gè)函數(shù)的輸出是:輸出:doingcancel
在GoLang中取消上下文時(shí)如何在函數(shù)中立即返回?
寶慕林4294392
2022-10-17 16:47:34