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
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
", i1, i2)
This line will print:
i1: main.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}
.