代码之家  ›  专栏  ›  技术社区  ›  zangw

“type DoNotCompare[0]func()”如何阻止Golang中的可比性

  •  1
  • zangw  · 技术社区  · 4 年前

    每protobuf pragma

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

    我不明白为什么 DoNotCompare 可能会阻止可比性,并尝试用以下代码理解。不幸的是,我失败了。这个 NonCompare struct似乎可以进行比较。

    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)
    

    我还缺什么吗?

    1 回复  |  直到 4 年前
        1
  •  2
  •   icza    4 年前

    这项预防工作是在建筑上进行的 == 接线员,不是你的电话 Compare() 方法确实如此。当然,它可以做任何你想做的事。

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

    fmt.Println(nc1 == nc2)
    

    出现编译时错误:

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

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

    等式运算符==和!=应用于以下操作数: 可比较的 .排序运算符<<=>,和>=应用于按顺序排列的操作数。这些术语和比较结果的定义如下:

    • [...]
    • 如果结构值的所有字段都具有可比性,则结构值具有可比性。如果两个结构值对应的非- blank 领域是平等的。
    • 如果数组元素类型的值具有可比性,则数组值具有可比性。如果两个数组的对应元素相等,则两个数组值相等。

    [...] 切片、贴图和函数值不可比较。

    一系列大小 0 这样字段的大小将为0,而不会向使用它的结构中添加任何额外内容。请注意,只有将0大小的字段放在第一位时,才能保证这一点。有关详细信息,请参阅 Struct has different size if the field order is different .