在上一篇文章里面 我们介绍了协程的概念以及如何通过通道来退出协程。在这篇文章里面,我们继续讲解如何通过context来退出协程。
context的解释如下(官方解释):
Incoming requests to a server should create a Context, and outgoing calls to servers should accept a Context. The chain of function calls between them must propagate the Context, optionally replacing it with a derived Context created using WithCancel, WithDeadline, WithTimeout, or WithValue. When a Context is canceled, all Contexts derived from it are also canceled.
意思是,context是来传递信息的:服务端可以创建一个context,而请求方应该接受这个context;在方法的调用链中,必须传递这个context,在创建context中,可选参数有WithCancel