打印变量会改变之前代码的结果。

huangapple go评论76阅读模式
英文:

Printing variables changes the previous code results

问题

我有以下代码:

package main

import "fmt"

type MyStruct struct {
}

func main() {
	a := &MyStruct{}
	b := &MyStruct{}

	fmt.Println(a == b)
	fmt.Println(*a == *b)
}

预期输出结果为:

false
true

但是,如果我在末尾添加两个Print语句,代码如下:

package main

import "fmt"

type MyStruct struct {
}

func main() {
	a := &MyStruct{}
	b := &MyStruct{}

	fmt.Println(a == b)
	fmt.Println(*a == *b)
	fmt.Println(&a)
	fmt.Println(&b)
}

输出结果变成了我没有预料到的:

true
true
0xc0000ae018
0xc0000ae020

为什么在第一种情况下结果是true

英文:

I have the following code:

package main

import "fmt"

type MyStruct struct {
}

func main() {
	a := &MyStruct{}
	b := &MyStruct{}

	fmt.Println(a == b)
	fmt.Println(*a == *b)
}

Which as expected outputs

false
true

But, if I add two Print statements at the end like this:

package main

import "fmt"

type MyStruct struct {

}

func main() {
   a := &MyStruct{}
   b := &MyStruct{}

   fmt.Println(a == b)
   fmt.Println(*a == *b)
   fmt.Println(&a)
   fmt.Println(&b)
}

The output becomes something I did not expect:

true
true
0xc0000ae018
0xc0000ae020

Why does it become true in the first case?

答案1

得分: 3

根据Go语言的规范

> 指向不同的零大小变量的指针可能相等,也可能不相等。

MyStructstruct{},它是一个零大小的类型。因此,a == b可能为truefalse

英文:

From the Go language specification:

> Pointers to distinct zero-size variables may or may not be equal.

MyStruct is struct{}, which is a zero-size type. Hence, a == b may be true or false.

huangapple
  • 本文由 发表于 2022年12月10日 14:29:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/74750875.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定