golang 为什么比较两个指向结构的变量表现不同?

标签 go pointers struct comparison

我创建了两个相同结构的实例,当我比较两个变量指向结构的实例时,对输出感到困惑。

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/

相关文章:

go - sync.Mutex 或 http.HandleFunc 不工作

go - Boltdb 中的批处理操作

go - 追加不是线程安全的?

尝试显示指针值和指针地址时代码未运行

c++ - Eigen::Ref 传递指针

mongodb - 使用 time.Time 字段插入文档时设置默认日期

结构中的 C 内存错误

go func(*DB) 不存在该行时查询返回

c++ - 使用空指针在C++中打印数组

c++ - 如何在 OpenMP 中将对象或结构定义为 threadprivate?