3

我一直在阅读来自 github.com/lib/pq 的一些 Golang 代码,它提供了与 postgres 数据库交互的驱动程序。

在我遇到的代码

go func() {
    select {
    case <-done:
        _ = cn.cancel()
        finished <- struct{}{}
    case <-finished:
    }
}()

取消函数如下所示

func (cn *conn) cancel() error

据我所知,下划线没有被用作关于类型的静态断言(因此编译器不会评估任何副作用,据我所知(如本例所示))并且它不是t 第二个参数,作者可能希望将其丢弃。

总结:为什么要将取消函数的结果(错误)分配给下划线?

4

2 回答 2

5

代码必须正确。为了确保代码正确,代码必须是可读的。


围棋的第一条规则:检查错误。


func (cn *conn) cancel() error

如果我写

cn.cancel()

我是忘记检查错误还是决定丢弃错误值?

但是,如果我写

_ = cn.cancel()

我没有忘记检查错误,我确实决定丢弃错误值。


Go 编程语言规范

空白标识符

空白标识符由下划线字符 _ 表示。它用作匿名占位符而不是常规(非空白)标识符,并且在声明、操作数和赋值中具有特殊含义。

作业

空白标识符提供了一种忽略赋值中右侧值的方法:

于 2018-12-30T11:07:59.310 回答
3

The blank identifier “_” is a special anonymous identifier. When used in an assignment, like this case, it provides a way to explicitly ignore right-hand side values. So, the developer has decided to ignore/discard the error returned from this method call.

A few reasons why they may have done this (based on a quick glance at the method call and context, my guess is 3 or 4):

  1. The method call is guaranteed to succeed in this context.
  2. The error is already handled sufficiently within the method call; no reason to handle it again.
  3. The error doesn’t matter (eg the relevant process is going to end anyway and the outcome will be the same as if the method call has succeeded without error).
  4. The developer was in a hurry to get something working, ignored the error to save time, then failed to come back and handle the error.
于 2018-12-30T09:55:47.003 回答