英文:
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 { // <<<< 这里有一个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 <- conn
}()
select { // <<<< golint warning here
case conn := <-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 := <-pool.connections:
return pool.packConn(conn), nil
}
With:
conn := <-pool.connections
return pool.packConn(conn), nil
Or even:
return pool.packConn(<-pool.connections), nil
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论