golang 里的一些奇奇怪怪的东西
首吐槽:select
不是 switch 语法,每个 case 必须是一个通信操作,要么是发送要么是接收,如果有满足则执行并退出,否则一直循环检测,如果没有 case 可运行,它将阻塞。
他是如何轮询的:是为了避免饥饿问题,随机
一个 case 都没有的 select{}
空的 select
语句会直接阻塞当前 Goroutine,导致 Goroutine 进入无法被唤醒的永久休眠状态。
我猜 waitgroup 使用这个方式实现。
Scope 最小化
variable 从定义到使用"一条龙"
if 语句两句话:
为什么不可以把分号;改成与 &&?
我们看下 tour of go 中的表述:
Like
for
, theif
statement can start with a short statement to execute before the condition.Variables declared by the statement are only in scope until the end of the
if
.
function 从定义到调用“一条龙”
go func() {c, err := g.connect(ctx, addr)if err != nil {log.Printf("error to connect address %v, need to remove from conection pool", addr)
类型断言放后面
OK👌断言
还有一行三条语句的例子(for 循环的 3 个参数,好理解)
还有无参数的写法
相当于 while true
"named" return value: return 空就是 return 一切
它等于
官方解释:
The expression list may be empty if the function's result type specifies names for its result parameters. The result parameters act as ordinary local variables and the function may assign values to them as necessary. The "return" statement returns the values of these variables.
Regardless of how they are declared, all the result values are initialized to the zero values for their type upon entry to the function. A "return" statement that specifies results sets the result parameters before any deferred functions are executed.
pointer *
对于一个 interface,有的方法实现是引用传递类型,有的是值传递类型混合的方式怎么处理,
However, a pointer to the struct will implement the interface, so changing your Create
method to do return &obj
should get things working.
The underlying problem is that your modified SetSomeField
method is no longer in the method set of Implementation
. While the type *Implementation
will inherit the non-pointer receiver methods, the reverse is not true.
slice 里面三个点
用来在初始化 slice 的时候,自动推导出 slice 的长度
context done channel 怎么查谁发来的结束信号去 cancel?
Go 语言的并发模型:pipelines&cancellation
slice 后面三个点...
function 对参数类型,是不定场参数,slice 后面跟 3 个点(...), 表示将 slice 展开成为一个不定长参数
空 interface 和空 strut
interface {} vs struct {}
empty structs, and that is the chan struct{}
construct used for signaling between go routines
Empty interfaces are used by code that handles values of unknown type. For example, fmt.Print
takes any number of arguments of type interface{}
.
版权声明: 本文为 InfoQ 作者【不登山的小鲁】的原创文章。
原文链接:【http://xie.infoq.cn/article/2f583693dd1cfeaf593959adc】。文章转载请联系作者。
评论