What is the difference between struct {int} and struct {int int}?

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

package main import "fmt" func main() { a := struct{int}{1} b := struct{int int}{1} fmt.Println(a,b) a.int=2 b.int=a.int fmt.Println(a,b) //a = b } 

They look the same:

 $ go run a.go {1} {1} {2} {2} 

But if you uncomment a = b , it says:

 $ go run a.go # command-line-arguments ./a.go:10: cannot use b (type struct { int int }) as type struct { int } in assignment 

However, struct{a,b int} and struct{a int;b int} equivalent:

 package main func main() { a := struct{a,b int}{1,2} b := struct{a int;b int}{1,2} a = b b = a } 

?

+5
source share
1 answer

struct { int } is a structure with an anonymous field of type int .

struct { int int } is a structure with a field named int type int .

int not a keyword; it can be used as an identifier.

The types of structure are not identical; corresponding fields do not have the same name.

A field declared with a type but without an explicit field name is an anonymous field, and an unqualified type name acts as the name of an anonymous field. Therefore, the field names a.int and b.int valid. For instance,

 a := struct{ int }{1} b := struct{ int int }{1} a.int = 2 b.int = a.int 

Go programming language specification

Types of designs

A structure is a sequence of named elements called fields, each of which has a name and type. Field names can be specified explicitly (IdentifierList) or implicitly (AnonymousField). Inside the structure, Non-empty field names must be unique.

 StructType = "struct" "{" { FieldDecl ";" } "}" . FieldDecl = (IdentifierList Type | AnonymousField) [ Tag ] . AnonymousField = [ "*" ] TypeName . 

A field declared with a type but without an explicit field name is an anonymous field, also called an inline field or an attachment, type in a struct. A nested type must be specified as a type name T or as a pointer to a type name without an * T interface, and T itself may not be a pointer type. An unqualified type name acts like a name field.

Keywords

The following keywords are reserved and cannot be used as identifiers.

 break default func interface select case defer go map struct chan else goto package switch const fallthrough if range type continue for import return var 

Enter 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. It is assumed that two anonymous fields have the same name. Lower case field names from different packages are always different.

+9
source

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


All Articles