go-staticcheck: should use a simple channel send/receive instead of select with a single case (S1000)

huangapple go评论118阅读模式
英文:

go-staticcheck: should use a simple channel send/receive instead of select with a single case (S1000)

问题

我正在使用Go 1.16.4版本。我正在尝试处理以下代码:

func (pool *myConnPool) GetPooledConnection() (*myConnection, error) {
	go func() {
		conn, err := pool.createConn()
		if err != nil {
			return
		}
		pool.connections <- conn
	}()
	select { // &lt;&lt;&lt;&lt; 这里有一个golint警告
	case conn := <-pool.connections:
		return pool.packConn(conn), nil
	}
}

我收到了以下Go linter警告:在代码中标记的位置处,警告为should use a simple channel send/receive instead of select with a single case (S1000)。有人可以解释如何修复吗?我对Go通道还不太熟悉。

英文:

I am using Go 1.16.4. I am trying to deal with such code:

func (pool *myConnPool) GetPooledConnection() (*myConnection, error) {
	go func() {
		conn, err := pool.createConn()
		if err != nil {
			return
		}
		pool.connections &lt;- conn
	}()
	select { // &lt;&lt;&lt;&lt; golint warning here
	case conn := &lt;-pool.connections:
		return pool.packConn(conn), nil
	}
}

I am getting following Go linter warning: should use a simple channel send/receive instead of select with a single case (S1000) at the point marked in the code. Can anyone please explain how to fix that? I am not yet too experienced with Go channels.

答案1

得分: 23

代码中的select语句在只有一个case的情况下是没有意义的,linter正在提醒你这一点。为了解决这个问题,你可以将代码替换为以下形式:

conn := <-pool.connections
return pool.packConn(conn), nil

甚至可以简化为:

return pool.packConn(<-pool.connections), nil
英文:

The linter is telling you that your use of select is meaningless with only a single case.
To solve the problem, replace this:

select {
case conn := &lt;-pool.connections:
    return pool.packConn(conn), nil
}

With:

conn := &lt;-pool.connections
return pool.packConn(conn), nil

Or even:

return pool.packConn(&lt;-pool.connections), nil

huangapple
  • 本文由 发表于 2021年5月31日 05:11:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/67765853.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定