Why does this anonymous func return the same instance of the structure?

package main import "fmt" type fake struct { } func main() { f := func() interface{} { return &fake{} } one := f() two := f() fmt.Println("Are equal?: ", one == two) fmt.Printf("%p", one) fmt.Println() fmt.Printf("%p", two) fmt.Println() } 

( http://play.golang.org/p/wxCUUCyz98 )

Why is this anonymous func returning the same instance of the requested type, and how can I make it return a new one for each call?

+4
source share
2 answers

You are comparing two interfaces with one == two . Let's see what the language specification says by the meaning of this expression:

Interface values ​​are comparable. Two interface values ​​are equal if they have the same dynamic types and equal dynamic values, or if both are nil.

The pointer values ​​are comparable. Two pointer values ​​are equal if they point to the same variable or both are nil. Pointers to various variables of zero size may or may not be equal.

In your example, both the one and two values ​​are the values ​​of both interfaces, and they have the same dynamic type ( *fake ). Their dynamic values ​​are simultaneously pointers to an object with a zero size, and, as you can read above, in this case there may or may not be equality.

Given this, you can solve your problem by not using pointers for structures with zero size as unique values. Perhaps use int instead?

It might look like this:

 type fake int func main() { var uniq fake f := func() interface{} { uniq++ return uniq } ... } 

It is not clear what you are trying to achieve, so this may or may not be a good solution for you.

+6
source

Last paragraph of language specification:

The type of a structure or array is 0 if it does not contain fields (or elements, respectively) whose size is greater than zero. Two different zero-sized variables can have the same memory address.

http://golang.org/ref/spec#Size_and_alignment_guarantees

So, as indicated in the accepted answer, you will see what you expect if you use a non-empty structure.

+1
source

Source: https://habr.com/ru/post/1482716/


All Articles