Go Tutorial · Data Structures · Lesson 15 of 30
Go Structs
Group fields into structs, struct literals, embedding and tags.
Defining structs
A struct groups named fields — Go's way of modelling data (there are no classes):
package main
import "fmt"
type User struct {
Name string
Email string
Age int
}
func main() {
u := User{Name: "Ada", Email: "[email protected]"}
u.Age = 36
fmt.Println(u.Name, u.Age)
fmt.Printf("%+v\n", u)
anon := struct {
X, Y int
}{3, 4}
fmt.Println(anon)
p := &u // pointer to struct: fields accessed the same way
p.Age++
fmt.Println(u.Age)
}
Output
Ada 36
{Name:Ada Email:[email protected] Age:36}
{3 4}
37Run this on your computer — see “Get Started” for setup.
Embedding
Embedding a struct promotes its fields and methods — composition instead of inheritance:
package main
import "fmt"
type Person struct {
Name string
City string
}
func (p Person) Greet() string {
return "Hi, I'm " + p.Name
}
type Employee struct {
Person // embedded
Title string
}
func main() {
e := Employee{Person: Person{Name: "Lin", City: "Oslo"}, Title: "Engineer"}
fmt.Println(e.Name, e.City, e.Title) // promoted fields
fmt.Println(e.Greet()) // promoted method
}
Output
Lin Oslo Engineer Hi, I'm Lin
Run this on your computer — see “Get Started” for setup.
Struct tags
Tags are metadata read by packages like encoding/json: `json:"name"` — see JSON.
Test yourself
What does Go use instead of class inheritance?
extendsEmbedding (composition)PrototypesMixins
Show answer
Answer: Embedding (composition)