'type DoNotCompare [0]func()' 如何防止 Golang 中的可比性

How does 'type DoNotCompare [0]func()' prevent comparability in Golang

每个 protobuf pragma

`type DoNotCompare [0]func()`
DoNotCompare can be embedded in a struct to prevent comparability

我很困惑为什么DoNotCompare会阻止可比性,并尝试通过以下代码来理解。不幸的是,我失败了。 NonCompare 结构似乎具有可比性。

type DoNotCompare [0]func()

type NonCompare struct {
    DoNotCompare

    ii int8
}

type Comparer interface {
    Compare(b NonCompare) int
}

func (a NonCompare) Compare(b NonCompare) int {
    if a.ii > b.ii {
        return 1
    }
    return 0
}

func main() {
    var nc1 = NonCompare{ii: 3}
    var nc2 = NonCompare{ii: 5}

    nc1.Compare(nc2)

我有什么遗漏吗?

预防工作针对内置的 == 运算符,而不是针对您的 Compare() 方法的作用。当然,它可以为所欲为。

但是如果你尝试使用 ==:

fmt.Println(nc1 == nc2)

您收到 compile-time 错误:

./prog.go:30:18: invalid operation: nc1 == nc2 (struct containing DoNotCompare cannot be compared)

原因是因为 func() 类型(或任何函数类型)的值不可比较,所以 [0]func() 值也不可比较。具有 non-comparable 类型字段的结构也不可比较。规则列于 Spec: Comparison operators:

The equality operators == and != apply to operands that are comparable. The ordering operators <, <=, >, and >= apply to operands that are ordered. These terms and the result of the comparisons are defined as follows:

  • [...]
  • Struct values are comparable if all their fields are comparable. Two struct values are equal if their corresponding non-blank fields are equal.
  • Array values are comparable if values of the array element type are comparable. Two array values are equal if their corresponding elements are equal.

[...] Slice, map, and function values are not comparable.

使用大小为 0 的数组,因此字段的大小将为 0,不会向使用它的结构添加任何额外内容。请注意,只有将 0 大小的字段放置到第一名。有关详细信息,请参阅