为什么在Go中,对两个存放着空结构体的接口变量进行比较时,添加fmt.Printf会改变它们是否相等的结果?
我在Go中观察到一种奇怪的行为:存在fmt.Printf语句会影响接口比较的布尔结果。
环境:
go version go1.25.6 darwin/amd64
package main
import "fmt"
type Animal interface {
Name() string
}
type Cat struct {
}
func (c Cat) Name() string {
return "cat"
}
func main() {
var c1 Animal = new(Cat)
var c2 Animal = new(Cat)
fmt.Println(c1 == c2)
fmt.Printf("%p,%p", c1, c2)
}
输出:
true
0x56d83c0,0x56d83c0
删除倒数第二行后
package main
import "fmt"
type Animal interface {
Name() string
}
type Cat struct {
}
func (c Cat) Name() string {
return "cat"
}
func main() {
var c1 Animal = new(Cat)
var c2 Animal = new(Cat)
fmt.Println(c1 == c2)
// fmt.Printf("%p,%p", c1, c2)
}
输出:
false
为什么打印会影响比较结果?
解决方案
在 语言规范 中,你有这段特定措辞,使这两种行为都同样合法:
指向不同的 零大小 变量的指针,可能相等,也可能不相等。
fmt.Printf 可能会影响编译器在逃逸分析上投入的工作量,这可能会影响它如何分配这两个结构体。
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。