GOOS指的是目标操作系统
GOARCH指的是目标处理器的架构
goland 配置goroot:从官网下载sdk
goland 配置gopath:src的上一级,支持多个,当有多个资源时,go get默认第一个使用
Err方法:返回取消的错误原因,Context被取消原因
Go支持匿名函数,如果我们某个函数只是希望使用一次,可以考虑使用匿名函数,匿名函数也可以实现多次调用
- WithTimeout
import "time"
// WithTimeout设置超时时间,some函数将ctx传下去,超过设定时间会自动调用cancel
func exec() {
ctx, cancel:= context.WithTimeout(context.Background(), 500*time.Millisecond)
defer cancel()
some(ctx)
}
- WithDeadline
import "time"
// WithDeadline是设置具体时间点,some函数将ctx传下去,超过设定时间会自动调用cancel
func exec() {
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(500*time.Millisecond))
defer cancel()
some(ctx)
}
- WithCancel
import "time"
// WithCancel是根据具体情况手动调用cancel
func exec() {
ctx, cancel := context.WithCancel(context.Background())
deadline = time.Now().Add(500*time.Millisecond)
if time.Now().After(deadline) {
cancel()
}
}
Done方法:返回一个只读的chan,类型为struct{},我们在goroutine中,如果该方法返回的chan可以读取,则意味着context已经发起了取消请求,我们通过Done方法收到这个信号后,就应该做清理操作,然后退出goroutine,释放资源
select就是用来监听和channel有关的IO操作,当 IO 操作发生时,触发相应的动作。
如果连default都没有,则select语句会一直阻塞,直到至少有一个IO操作可以进行
// 创建计时器,1s后触发
timer := time.NewTimer(time.Second)
select {
// 收到计时器的信号后触发
case <-timer.C:
xxx
case <-ctx.Done(): //当ctx收到取消的信号,执行done操作停止
timer.Stop()
}
//对于for select中的break是无法 退出到for循环外,只能goto实现
for {
select {
case <-time.After(time.Second * time.Duration(2)):
break
}
}