Structs
A struct gathers fields into a value. Tags are for encoders. Embedding is not inheritance.
A struct is a set of fields. A struct value is copied whole if you pass it without a pointer.
type User struct {
Name string
Age int
}
func Adult(u User) bool {
return u.Age >= 18
}
Unset fields receive zeros. The literal User{Name: "Ann", Age: 18} is better written with field names: the field order can then change without breaking callers. A literal without names, User{"Ann", 18}, breaks on any inserted field.
A tag is a string after a field. Packages read it through reflect. The language itself does not execute the tag.
type User struct {
Name string `json:"name"`
}
encoding/json will take the name name. A typo in a tag is not a compile error. A test of the encoding catches it.
Embedding is written as a field with no name:
type Admin struct {
User
Scope string
}
The fields and methods of User are promoted onto Admin. This is composition, not inheritance: no dynamic type "an admin is a user" appears by itself for methods with a value receiver. The outer type can declare a method with the same name and shadow the inner one. Do not build deep towers of embedding. One embedding, so you do not write admin.User.Name, is fine. Three levels for the sake of "OOP" are not.
Practice
A literal with names
Why write field names in a struct literal, rather than only values in order?
- Without names the literal does not compile
- So that adding a field does not break or confuse callers
- Names are needed only when there are json tags
- That way the struct starts being passed by pointer
Coming of age
Declare a struct
Userwith fieldsName stringandAge int. WriteAdult(u User) bool: true when the age is not less than 18.Embedding
What comes closest to describing struct embedding in Go?
- Inheritance with virtual methods
- Composition: fields and methods of the inner type become available directly
- Copying fields at compile time into a separate sum type
- A way to make every field exported