Beginner Fundamentals

Structs

A struct groups related fields into a single type. Structs are how you model real-world data in Go.

Defining a struct

type Person struct {
    Name string
    Age  int
}

Creating values

You can set fields by name or by position.

p := Person{Name: "Ada", Age: 36}
fmt.Println(p.Name) // Ada

q := Person{"Alan", 41}
fmt.Println(q.Age) // 41

Updating fields

Access and change fields with a dot.

p.Age = 37
fmt.Println(p.Age) // 37

Methods

A method is a function with a receiver, attaching behavior to a struct.

func (p Person) Greet() string {
    return "Hi, I'm " + p.Name
}

fmt.Println(p.Greet()) // Hi, I'm Ada

Use a pointer receiver when the method needs to change the struct.

func (p *Person) Birthday() {
    p.Age++
}

p.Birthday()
fmt.Println(p.Age) // 38