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/

相关文章:

签名中带有数组类型的 ccall 从 Julia 调用 C 中的结构

c++ - 非常量成员引用在 const 对象上是可变的吗?

结构中数组的 C Malloc

http - 当请求有正文时,Go http 上下文无法捕获取消信号(curl, postman )

go - "%b"在 fmt.Printf 中对 float64 有什么作用?二进制格式的 float64 中的 Min subnormal positive double 是什么?

go - 如何在 GoLang 中找到 json.Unmarshalled() 对象的长度?

c++ - 方法调用链接;返回指针还是引用?

c - 将输入读入动态大小的 int?

go - 不能将 bufio.ReadString{} 与 ioutil.ReadFile() 一起使用

c - 如何在没有指针地址的情况下将结构指针分配为零并在下面的代码中查找结构的 sizeof ?