go-staticcheck:应该使用简单的通道发送/接收,而不是使用单个案例进行选择(S1000)

iva*_*ukr 9 channel go static-code-analysis

我正在使用 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 warning here
    case conn := <-pool.connections:
        return pool.packConn(conn), nil
    }
}
Run Code Online (Sandbox Code Playgroud)

我收到以下 Go linter 警告:should use a simple channel send/receive instead of select with a single case (S1000)在代码中标记的位置。谁能解释一下如何解决这个问题吗?我对 Go 通道还不太有经验。

Fli*_*mzy 26

linter 告诉您,如果select只有一个case. 要解决该问题,请替换以下内容:

select {
case conn := <-pool.connections:
    return pool.packConn(conn), nil
}
Run Code Online (Sandbox Code Playgroud)

和:

conn := <-pool.connections
return pool.packConn(conn), nil
Run Code Online (Sandbox Code Playgroud)

甚至:

return pool.packConn(<-pool.connections), nil
Run Code Online (Sandbox Code Playgroud)