相等的指针是不同的吗?

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

Equal pointers are different?

问题

这段代码创建了两个接口变量,它们都指向同一个指针。打印输出表明它们是同一个指针(而不是存储ss2的副本)。然而,最后一个打印输出显示i1i2不相等。为什么呢?

package main
import "fmt"
func main() {
    var s T = &struct{string}{}
    var s2 *struct{string} = s
    var i1 interface{} = s
    var i2 interface{} = s2
    fmt.Println(s)
    s.string = "s is i1"
    fmt.Println(i1)
    s.string = "s is i2"
    fmt.Println(i2)
    fmt.Println(i1==i2)
}

type T *struct{string}

输出结果如下:

&{}
&s is i1
&s is i2
false

为什么i1i2不相等呢?

英文:

This code creates two interface variables from the same pointer. The prints demonstrate that they are the same pointer (as opposed to storing copies of s and s2). Yet, the last print says i1 is not the same as i2. Why?

package main
import "fmt"
func main() {
    var s T = &struct{string}{}
    var s2 *struct{string} = s
    var i1 interface{} = s
    var i2 interface{} = s2
    fmt.Println(s)
    s.string = "s is i1"
    fmt.Println(i1)
    s.string = "s is i2"
    fmt.Println(i2)
    fmt.Println(i1==i2)
}

type T *struct{string}

<!

$ go run a.go
&amp;{}
&amp;{s is i1}
&amp;{s is i2}
false

答案1

得分: 3

这是Go语言规范中关于比较接口值的说明:

如果两个接口值具有相同的动态类型和相等的动态值,或者两者都为nil值,则它们是相等的。

i1中的值具有命名类型Ti2中的值具有匿名类型*struct{string}。由于这两个值具有不同的动态类型,所以这两个接口值是不相等的。

要查看类型,请将以下行添加到您的程序中:

fmt.Printf("i1: %T, i2: %T\n", i1, i2)

这行代码将打印出:

i1: main.T, i2: *struct { string }
英文:

Here's what the Go langauge specification says about comparing interface values:

> Two interface values are equal if they have identical dynamic types and equal dynamic values or if both have value nil.

The value in i1 has the named type T. The value in i2 has the anonymous type *struct{string}. Because the two values have different dynamic types, the interface values are not equal.

To see the types, add this line to your program:

fmt.Printf(&quot;i1: %T, i2: %T\n&quot;, i1, i2)

This line will print:

i1: main.T, i2: *struct { string }

答案2

得分: 2

这类似于检查 error 值与 nil 的情况,可以在这个常见问题解答中找到相关内容。基本上,为了使相等性通过,它们必须具有相同的值和类型,但 i1 是类型 T,而 i2 是类型 *struct{string}

英文:

This is similar to the checking an error value against nil which is covered in this FAQ, basically for the equality to pass they must be of the same value and type but i1 is of type T and i2 is of type *struct{string}.

huangapple
  • 本文由 发表于 2014年9月10日 00:16:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/25749484.html
匿名

发表评论

匿名网友

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

确定