您的位置 首页 golang

Go 2.0 这两个特性还是值得期待的

for range

range 这个坑之前文章已经分享过,这里再写一个新的

 type Foo  struct  {
  bar string
}

func main() {
  list := []Foo{{"A"}, {"B"}, {"C"}}

  cp := make([]*Foo, len(list))
  for i, value := range list {
    cp[i] = &value
  }
  fmt.Printf("cp: %q\n", cp)
}  

看过之前的文章的人应该都猜出来输出的结果了

 [C C C]  

所以在 Go 2.0 将支持这种 for range,这样我们就可以安心地使用 for range了。

确定性select

这个错误不容易被发现

 for {
  select {
  case <-doneCh: // 或者使用 <-ctx.Done():
    return
  case thing := <-thingCh:
    // 5秒超时
  case <-time.After(5*time.Second):
    return fmt.Errorf("timeout")
  }
}  

上面有个很细节的点:当select 在两个case同时满足的时候,到底执行哪个 case 将成为一个玄学。比如上面的 doneCh 和 thingCh 可能在一次select 里面同时满足。

为此Go 2.0 将会改成确定性的,比如case 有先后顺序,那么就可以保证 doneCh 先执行了。

文章来源:智云一二三科技

文章标题:Go 2.0 这两个特性还是值得期待的

文章地址:https://www.zhihuclub.com/99500.shtml

关于作者: 智云科技

热门文章

网站地图