我创建了两个相同结构的实例,当我比较两个变量指向结构的实例时,对输出感到困惑。
package main
import "fmt"
type Person struct {
name string
}
func main() {
p1 := &Person{name: "guru"}
p2 := &Person{name: "guru"}
fmt.Println(p1 == p2) // false, compares by address?
p3 := Person{name: "guru"}
p4 := Person{name: "guru"}
fmt.Println(p3 == p4) // true , why? compares by content?
}
== 运算符是否像重载运算符一样工作?
最佳答案
p1 == p2
是指针比较,比较指针值(内存地址)。由于您使用了 2 个复合文字(并获取了它们的地址),它们将指向 2 个不同的变量,因此地址将不同(因为 Person
的大小不为零)。 Spec: Composite literals:
Taking the address of a composite literal generates a pointer to a unique variable initialized with the literal's value.
p3 == p4
比较结构值,它逐个字段地比较它们,并且由于匹配的字段具有相等的值,比较结果将是 true
。
比较规则在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:
- [...]
- Pointer values are comparable. Two pointer values are equal if they point to the same variable or if both have value nil. Pointers to distinct zero-size variables may or may not be equal.
- [...]
- Struct values are comparable if all their fields are comparable. Two struct values are equal if their corresponding non-blank fields are equal.
关于golang 为什么比较两个指向结构的变量表现不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71054114/