What is the difference between struct {a int; b int} and struct {b int; a int}?

What is the difference between these two structures, except that they are not considered equivalent?

package main func main() {} func f1(s struct{a int;b int}) { f2(s) } func f2(s struct{b int;a int}) {} 

 $ go run a.go # command-line-arguments ./a.go:3: cannot use s (type struct { a int; b int }) as type struct { b int; a int } in argument to f2 

Note: this compiles:

 package main func main() {} func f1(s struct{a int;b int}) { f2(s) } func f2(s struct{a int;b int}) {} 
+5
source share
3 answers

"Structure field ordering is important at a low level." How?

This will affect reflection , for example func (v Value) Field(i int) Value :

The field returns the i-th field of structure v

The first field 'a' in the first structure will not be the same first in the second structure.
It will also affect serialization using marshaller methods (encoding package) .

+5
source

Type and Value Properties

Type id

Two types of structure are identical if they have the same sequence of fields, and if the corresponding fields have the same name and identical types and identical tags.

The corresponding field names are distinguished:

 s struct{a int;b int} 

against

 s struct{b int;a int} 
+4
source

From spec :

Two types of structures are identical if they have the same sequence of fields , and if the corresponding fields have the same name, same types, and identical tags. Two anonymous fields have the same name. Lower case field names from different packages are always different.

The field order of structures is important at a low level, so two structures with different sequences of fields cannot be safely considered equivalent.

+3
source

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


All Articles