Data Structures

Data Structures#

Go’s built-in composite types cover most needs: arrays, slices, maps, structs, and pointers.

Arrays#

Arrays have a fixed length that is part of the type.

var a [3]int = [3]int{1, 2, 3}
b := [...]string{"x", "y", "z"}   // length inferred

Slices#

A slice is a view over a backing array. It is the everyday list type.

xs := []int{1, 2, 3}
xs = append(xs, 4)
sub := xs[1:3]
length, capacity := len(xs), cap(xs)

Maps#

m := map[string]int{"one": 1, "two": 2}
m["three"] = 3
v, ok := m["two"]      // ok=true if present
delete(m, "one")

Structs#

type Person struct {
    Name string
    Age  int
}

p := Person{Name: "operator", Age: 36}

Interfaces#

Interfaces are satisfied implicitly. A type that has the right methods is automatically the right kind of thing.

type Stringer interface {
    String() string
}

Pointers#

p := &Person{Name: "operator"}
p.Name = "lovelace"      // automatic deref

Channels#

ch := make(chan int, 4)  // buffered
ch <- 1
v := <-ch
close(ch)