英文:
Equal pointers are different?
问题
这段代码创建了两个接口变量,它们都指向同一个指针。打印输出表明它们是同一个指针(而不是存储s
和s2
的副本)。然而,最后一个打印输出显示i1
和i2
不相等。为什么呢?
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
为什么i1
和i2
不相等呢?
英文:
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
&{}
&{s is i1}
&{s is i2}
false
答案1
得分: 3
这是Go语言规范中关于比较接口值的说明:
如果两个接口值具有相同的动态类型和相等的动态值,或者两者都为nil值,则它们是相等的。
i1
中的值具有命名类型T
。i2
中的值具有匿名类型*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("i1: %T, i2: %T\n", 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}
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论