go 的select必须要for{}吗

yaxiaomu · 2020-05-08 18:15:32 · 1512 次点击

3楼 @yaxiaomu 一个简单的例子:

官方提供的database/sql.go 文件中的代码

func (db *DB) conn(ctx context.Context, strategy connReuseStrategy) (*driverConn, error) {
    db.mu.Lock()
    if db.closed {
        db.mu.Unlock()
        return nil, errDBClosed
    }
    // Check if the context is expired.
    select {
    default:
    case <-ctx.Done():
        db.mu.Unlock()
        return nil, ctx.Err()
    }
    lifetime := db.maxLifetime
       // ... balabala
}
#8
更多评论

你自己没有运行看看吗 问题多多啊

#1

select当然不需要for配合啊,

最典型的例子。

你需要执行一个任务,又需要能在超时时做一些额外处理。

你那3个自立和效率没关系,功能都不一样

#2