gpt4 book ai didi

去结构比较

转载 作者:IT老高 更新时间:2023-10-28 13:05:32 24 4
gpt4 key购买 nike

Comparison operators 上的 Go 编程语言规范部分让我相信只包含可比较字段的结构应该是可比较的:

Struct values are comparable if all their fields are comparable. Two struct values are equal if their corresponding non-blank fields are equal.

因此,我希望以下代码能够编译,因为“Student”结构中的所有字段都是可比较的:

package main

type Student struct {
Name string // "String values are comparable and ordered, lexically byte-wise."
Score uint8 // "Integer values are comparable and ordered, in the usual way."
}

func main() {
alice := Student{"Alice", 98}
carol := Student{"Carol", 72}

if alice >= carol {
println("Alice >= Carol")
} else {
println("Alice < Carol")
}
}

但是,它 fails to compile与消息:

invalid operation: alice >= carol (operator >= not defined on struct)

我错过了什么?

最佳答案

你是对的,结构是comparable,但不是ordered(spec):

The equality operators == and != apply to operands that are comparable. The ordering operators <, <=, >, and >= apply to operands that are ordered.

...

  • Struct values are comparable if all their fields are comparable. Two struct values are equal if their corresponding non-blank fields are equal.

>=是一个有序的运算符,而不是一个可比的。

关于去结构比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39643251/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com