英文:
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语言的规范:
> 指向不同的零大小变量的指针可能相等,也可能不相等。
MyStruct
是struct{}
,它是一个零大小的类型。因此,a == b
可能为true
或false
。
英文:
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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论