Go: Embedding a primitive type?

Suppose we have this piece of code:

type User struct { int32 Name string } 

Can this type of attachment be useful?
Does int32 have any methods that others may call on User instances?
How can I access the int32 value that User is an attachment?

+3
source share
1 answer

The int32 type is a predefined type ; it has no methods. To check:

 fmt.Println(reflect.TypeOf(int32(0)).NumMethod()) // Prints 0 

You can reference all embedded fields using the name of an unqualified type as the field name ( Spec: structure types ), predefined types are no exception. See this example:

 u := User{3, "Bob"} fmt.Printf("%#v\n", u) u.int32 = 4 fmt.Println(u.int32) 

Conclusion (try on the Go Playground ):

 main.User{int32:3, Name:"Bob"} 4 

Primary reinforcement of using attachments:

  • built-in type methods get promoted, so it’s easier to implement interfaces (you don’t need to provide methods that get promoted)

  • you can "override" the methods of the built-in type (to the type of embedding): provide your own implementation, which will be called when using the value of your type of embedding

  • and the fields of the embedded type are received, so the code is shorter to refer to the promoted fields (field name is not specified).

int32 embedding predefined types, such as int32 , you do not get any advantages over using only a regular field (named, not embedded field), since the int32 type int32 not have any methods or fields.

Going forward, without having any advantages, you even have a disadvantage. Since names beginning with a name begin with lowercase letters, including them in them implicitly makes them unexported, so you can only refer to them in an embedding type declaration package. If you make them regular, named fields, you can use an uppercase name to make it exported, or a lower name to make it non-returning.

+8
source

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


All Articles