Structs, pointers, slices and maps
The data structures a rate limiter is built from: structs for state, pointers for shared mutable state, slices and maps for collections, with the gotchas that bite beginners.
Learning outcomes
- Define a struct, build values with composite literals, and write a NewX constructor.
- Explain what a pointer is, when to pass a value and when a pointer, and why a map of structs cannot be edited in place.
- Use slices, append, len and cap, and explain how slices share a backing array.
- Use maps, the comma-ok idiom and delete, and explain why a nil map panics on write.
- Create a map keyed by string that stores a pointer to a struct, which is the shape of a per-key limiter.
What you will learn
Most backend programs work with groups of related values. A rate limiter, for example, needs to remember information about each client: how many tokens remain, when a request was last processed, and which client the information belongs to.
Go provides three important tools for organizing and managing this data:
- Structs group related fields into one value.
- Pointers let multiple parts of a program refer to the same value.
- Slices and maps let you work with collections of values.
These concepts appear throughout the course. You will use structs to represent limiter state, maps to find state by client key, and pointers to update shared bucket values.
By the end of this lesson, you should be able to define these types, create and modify their values, understand copying and sharing, and recognize the data structure used by the first rate limiter.
Structs: grouping related data
A struct is a type that groups multiple named fields into one value. Each field has its own name and type.
Imagine a rate limiter that needs to remember how many requests a client has made. You could keep separate variables for the client key and request count, but that becomes difficult when you have many clients.
A struct gives these related values one logical identity.
package main
import "fmt"
type Client struct {
Key string
RequestCount int
Enabled bool
}
func main() {
client := Client{
Key: "user-42",
RequestCount: 3,
Enabled: true,
}
fmt.Printf("%+v\n", client)
}Output:
{Key:user-42 RequestCount:3 Enabled:true}The declaration creates a new type named Client. Its fields are Key, RequestCount, and Enabled.
The expression used to create the value is called a composite literal. It specifies the type and provides the values for its fields.
Composite literals
Prefer named fields when creating struct values:
client := Client{
Key: "user-42",
Enabled: true,
}Any field you leave out receives its zero value. In this example, RequestCount becomes 0.
You can also provide values without field names:
client := Client{"user-42", 3, true}This is called a positional composite literal. It depends on the order of the fields in the type. If someone adds or reorders fields, the meaning of the literal can become less obvious.
For application code, named fields are usually easier to read and safer to maintain.
Struct zero values
A struct's zero value is created by setting each field to that field's own zero value.
package main
import "fmt"
type Bucket struct {
Tokens float64
Enabled bool
Key string
}
func main() {
var bucket Bucket
fmt.Printf("%+v\n", bucket)
}Output:
{Tokens:0 Enabled:false Key:}This is useful because a struct can start in a valid, predictable state without explicitly initializing every field.
The zero value of a struct does not automatically make every possible operation valid. For example, a field that is a map still has a nil map as its zero value, and writing to that map will panic. You will see why shortly.
Constructors
A constructor is a function that creates and returns a value of a particular type. Go does not have a special constructor keyword. A constructor is an ordinary function, commonly named NewTypeName.
package main
import "fmt"
type Bucket struct {
Tokens float64
Key string
}
func NewBucket(key string, capacity float64) *Bucket {
return &Bucket{
Key: key,
Tokens: capacity,
}
}
func main() {
bucket := NewBucket("user-42", 10)
fmt.Printf("%+v\n", bucket)
}The constructor returns *Bucket, which means a pointer to a Bucket. The & operator obtains the address of the struct value.
Returning a pointer is common when a type represents state that should be updated through a shared reference. It also avoids copying the struct every time it is passed to a function.
A constructor is useful when creating a value requires consistent initialization. Instead of asking every caller to remember the initial token count, the constructor establishes that rule in one place.
Struct tags
A struct tag is metadata attached to a field. It is commonly used by libraries that encode or decode data.
type CreateUserRequest struct {
Name string `json:"name"`
Email string `json:"email"`
}The json:"name" tag tells Go's JSON encoding and decoding package to use name as the JSON field name.
You do not need to use tags for ordinary struct values. They become more important when you build HTTP request and response types and work with database models in later weeks.
Pointers: referring to existing values
A pointer stores the memory address of another value. Instead of holding the value itself, it tells the program where that value can be found.
The type *Bucket means a pointer to a Bucket.
Two operators are central to understanding pointers:
&valueobtains the address of a value.*pointeraccesses the value stored at the address.
Consider this example:
package main
import "fmt"
type Bucket struct {
Tokens float64
}
func main() {
bucket := Bucket{Tokens: 10}
pointer := &bucket
fmt.Println(pointer)
fmt.Println(*pointer)
}The variable bucket holds the struct value. The variable pointer holds its address. Dereferencing the pointer with *pointer gives access to the original struct.
Go also allows you to access struct fields through a pointer without explicitly dereferencing it.
package main
import "fmt"
type Bucket struct {
Tokens float64
}
func main() {
bucket := Bucket{Tokens: 10}
pointer := &bucket
pointer.Tokens = 7
fmt.Println(bucket.Tokens)
}Output:
7The assignment changes the original struct because pointer refers to that same value.
Copying a struct versus sharing a pointer
When you assign one struct value to another variable, Go copies the struct's fields.
package main
import "fmt"
type Bucket struct {
Tokens float64
}
func main() {
original := Bucket{Tokens: 10}
copied := original
copied.Tokens = 5
fmt.Println(original.Tokens)
fmt.Println(copied.Tokens)
}Output:
10
5The two variables contain independent struct values. Changing copied does not change original.
Now consider two pointers referring to the same struct:
package main
import "fmt"
type Bucket struct {
Tokens float64
}
func main() {
original := Bucket{Tokens: 10}
first := &original
second := first
second.Tokens = 5
fmt.Println(first.Tokens)
fmt.Println(second.Tokens)
fmt.Println(original.Tokens)
}Output:
5
5
5The pointer assignment copies the address, not the underlying struct. Both pointers refer to the same value.


This distinction matters when you design backend state. If every function receives a struct value, each function can work with its own copy. If functions receive pointers, they can refer to and update the same underlying value.
Passing values and pointers to functions
A function parameter receives a copy of the argument passed to it. This is true for both ordinary values and pointers.
When you pass a struct, the function receives a copy of the struct.
package main
import "fmt"
type Bucket struct {
Tokens float64
}
func consume(bucket Bucket) {
bucket.Tokens--
}
func main() {
bucket := Bucket{Tokens: 10}
consume(bucket)
fmt.Println(bucket.Tokens)
}Output:
10The function changed its local copy, not the caller's struct.
If the function receives a pointer, it receives a copy of the address. Both the caller and the function can still refer to the same struct.
package main
import "fmt"
type Bucket struct {
Tokens float64
}
func consume(bucket *Bucket) {
bucket.Tokens--
}
func main() {
bucket := Bucket{Tokens: 10}
consume(&bucket)
fmt.Println(bucket.Tokens)
}Output:
9Use a value parameter when the function should work with an independent copy or when the type is small and copying is appropriate.
Use a pointer parameter when the function needs to update the caller's value or when copying the value is undesirable.
A pointer can also be nil. A nil pointer does not refer to a value.
var bucket *Bucket
fmt.Println(bucket == nil)This prints true. Attempting to access a field through a nil pointer causes a runtime panic.
Slices: working with sequences
A slice is a flexible view over a sequence of values. It is one of the most common collection types in Go.
A slice has three important properties:
- A pointer to an underlying array, called its backing array.
- A length, which is the number of elements currently accessible through the slice.
- A capacity, which is the number of elements available from the slice's starting position to the end of its backing array.
You do not need to manage the backing array directly in ordinary code. Go provides built-in operations for creating and extending slices.
Creating slices
You can create a slice using a composite literal:
package main
import "fmt"
func main() {
counts := []int{3, 5, 2}
fmt.Println(counts)
fmt.Println(len(counts))
fmt.Println(cap(counts))
}Output:
[3 5 2]
3
3The len function returns the number of elements. The cap function returns the capacity.
You can also create a slice using make:
counts := make([]int, 3)This creates a slice with length three. Its elements are initialized to the zero value of int, which is 0.
You can provide a larger capacity:
counts := make([]int, 3, 10)This creates a slice with length three and capacity ten. The slice currently exposes three elements, but it can grow without immediately allocating a larger backing array.
Adding elements with append
Use the built-in append function to add elements to a slice.
package main
import "fmt"
func main() {
counts := []int{3, 5}
counts = append(counts, 2)
counts = append(counts, 8, 13)
fmt.Println(counts)
}Output:
[3 5 2 8 13]Always assign the result of append back to a slice variable. The operation may need to allocate a new backing array if the existing capacity is insufficient.
counts = append(counts, 10)This is important because the returned slice may refer to a different backing array than the original one.
Iterating with range
You can use range to visit every element in a slice.
package main
import "fmt"
func main() {
counts := []int{3, 5, 2}
for index, count := range counts {
fmt.Printf("index=%d count=%d\n", index, count)
}
}The loop provides the index and the element value. If you only need the element, use _ for the index:
for _, count := range counts {
fmt.Println(count)
}Slicing a slice
A slice expression creates another slice that refers to part of an existing slice.
package main
import "fmt"
func main() {
counts := []int{10, 20, 30, 40, 50}
selected := counts[1:4]
fmt.Println(selected)
fmt.Println(len(selected))
fmt.Println(cap(selected))
}Output:
[20 30 40]
3
4The expression counts[1:4] includes indexes 1, 2, and 3. The ending index is excluded.
The resulting slice starts at the second element of the original backing array. Its length is three, but its capacity is four because four positions remain from its starting point to the end of the backing array.
Slices can share a backing array
This is one of the most important details about slices.
Creating a slice from another slice does not necessarily copy the elements. The new slice usually refers to the same backing array.
package main
import "fmt"
func main() {
counts := []int{10, 20, 30, 40}
selected := counts[1:3]
selected[0] = 99
fmt.Println(counts)
fmt.Println(selected)
}Output:
[10 99 30 40]
[99 30]Changing selected[0] also changes counts[1] because both slices refer to the same array position.


If you need an independent copy, use copy with a destination slice of the required length.
package main
import "fmt"
func main() {
original := []int{10, 20, 30}
copied := make([]int, len(original))
copy(copied, original)
copied[0] = 99
fmt.Println(original)
fmt.Println(copied)
}Output:
[10 20 30]
[99 20 30]The two slices now contain independent values.
Nil slices and zero values
The zero value of a slice is nil.
package main
import "fmt"
func main() {
var counts []int
fmt.Println(counts == nil)
fmt.Println(len(counts))
fmt.Println(cap(counts))
}Output:
true
0
0A nil slice has length zero and capacity zero. It is safe to read its length and append to it.
counts = append(counts, 10)After this operation, counts is no longer nil.
A nil slice is not the same as an empty but initialized slice:
var first []int
second := []int{}
fmt.Println(first == nil)
fmt.Println(second == nil)The first prints true; the second prints false. Both have length zero.
Maps: looking up values by key
A map stores key-value pairs. You provide a key to find its associated value.
Maps are useful when you need to look up limiter state by a client identifier. Instead of searching through a list of every client, you can use the key directly.
Creating and using maps
A map declaration specifies the key type and value type.
package main
import "fmt"
func main() {
counts := map[string]int{
"user-42": 3,
"user-99": 5,
}
fmt.Println(counts["user-42"])
}Here, the keys are strings and the values are integers.
You can create an empty map using make:
counts := make(map[string]int)
counts["user-42"] = 3Unlike a nil slice, a nil map cannot be written to.
var counts map[string]int
fmt.Println(len(counts))This is safe and prints 0. But this assignment panics:
counts["user-42"] = 3The map's zero value is nil. A nil map can be read from and measured, but it cannot accept new entries. Initialize it with make or a map literal before writing.
Reading values and comma-ok
When you read a key that does not exist, Go returns the zero value of the map's value type.
counts := map[string]int{
"user-42": 3,
}
fmt.Println(counts["unknown"])This prints 0. But that result alone does not tell you whether the key is missing or whether the key exists with a stored value of zero.
Use the comma-ok pattern to distinguish the two cases:
count, ok := counts["user-42"]
if ok {
fmt.Println("found:", count)
} else {
fmt.Println("not found")
}The first result is the value. The second is a boolean indicating whether the key exists.
This is especially useful when zero is a valid value.
package main
import "fmt"
func main() {
counts := map[string]int{
"user-42": 0,
}
count, exists := counts["user-42"]
fmt.Println(count, exists)
missing, exists := counts["user-99"]
fmt.Println(missing, exists)
}Output:
0 true
0 falseBoth lookups return 0, but their boolean results are different.
Updating and deleting entries
Assigning to a key creates or replaces its value.
counts := make(map[string]int)
counts["user-42"] = 3
counts["user-42"] = 4Use the built-in delete function to remove an entry.
delete(counts, "user-42")Deleting a key that does not exist is safe. It does not cause a panic.
You can also iterate over a map with range.
package main
import "fmt"
func main() {
counts := map[string]int{
"user-42": 3,
"user-99": 5,
"user-17": 2,
}
for key, count := range counts {
fmt.Println(key, count)
}
}Map iteration order is unspecified. You should not expect entries to appear in insertion order or in sorted order. If output must be deterministic, collect and sort the keys before printing them.
You can delete entries while ranging over a map:
package main
import "fmt"
func main() {
counts := map[string]int{
"user-42": 0,
"user-99": 5,
"user-17": 0,
}
for key, count := range counts {
if count == 0 {
delete(counts, key)
}
}
fmt.Println(counts)
}This is permitted in Go. Entries that have not yet been reached may or may not be visited if they are removed during iteration. Do not write logic that depends on a particular iteration order.
Maps containing structs
Suppose you want to store a bucket for each client.
type Bucket struct {
Tokens float64
}
buckets := map[string]Bucket{
"user-42": {Tokens: 10},
}This map stores struct values directly.
However, this assignment does not compile:
buckets["user-42"].Tokens = 5A map lookup returns a copy of the stored value. Go does not allow you to modify a field directly on that temporary copy.
One way to update the value is to retrieve it, modify the local copy, and assign it back:
bucket := buckets["user-42"]
bucket.Tokens = 5
buckets["user-42"] = bucketThis works, but it requires an extra lookup and assignment whenever you need to update a field.
Maps containing pointers
An alternative is to store pointers to structs.
package main
import "fmt"
type Bucket struct {
Tokens float64
}
func main() {
buckets := map[string]*Bucket{
"user-42": {
Tokens: 10,
},
}
buckets["user-42"].Tokens = 5
fmt.Println(buckets["user-42"].Tokens)
}Output:
5The map lookup returns a pointer value. Accessing the field through that pointer modifies the original bucket.
This is the shape you will use for the token bucket:
map[string]*BucketThe key is a client identifier, and the value is a pointer to that client's bucket.
Designing a per-key limiter
A bucket needs to remember its current token count. It will also need to remember when it was last updated so that the limiter can calculate how many tokens to add over time.
For now, keep the time field as an integer. You will learn Go's time package and duration handling in lesson 1.10.
package main
import "fmt"
type Bucket struct {
Tokens float64
LastAt int64
}
func main() {
buckets := make(map[string]*Bucket)
buckets["user-42"] = &Bucket{
Tokens: 10,
LastAt: 1000,
}
buckets["user-99"] = &Bucket{
Tokens: 5,
LastAt: 1000,
}
bucket := buckets["user-42"]
bucket.Tokens -= 1
fmt.Printf("%+v\n", bucket)
}Output:
&{Tokens:9 LastAt:1000}The map gives you a way to find the bucket for a client. The pointer allows you to update that client's existing bucket without copying the entire struct back into the map.
This example introduces the data structure, not the complete limiter. You will add synchronization and time-based refill behavior in later lessons.
Common mistakes to avoid
- Assuming a struct assignment creates a shared reference. Struct assignment copies the value.
- Assuming a pointer assignment copies the underlying struct. It copies the address, so both pointers can refer to the same value.
- Forgetting to initialize a map before writing to it. A nil map allows reads but panics on writes.
- Forgetting to assign the result of
appendback to the slice variable. - Assuming two slices created from the same slice have independent backing arrays. They may share the same array.
- Using a map lookup's zero value to determine whether a key exists. Use the comma-ok result when existence matters.
- Expecting map iteration to follow insertion order. Map iteration order is unspecified.
- Trying to modify a struct field directly through a map of struct values. Retrieve, modify, and assign it back, or store pointers instead.
- Assuming a map of pointers can never contain nil. A key may exist with a nil pointer value, so check before dereferencing when that is possible.
Knowledge assessment
Consider two variables holding struct values and two variables holding pointers to the same struct. Which statement correctly describes their behavior?
Practical applications
- Practice exercise 1.8, Write your first Go program: Use struct values, pointers, slices, and maps in small standalone examples to practice creating and modifying data.
- Exercise 1.11, Token bucket: Use a
Bucketstruct and amap[string]*Bucketto maintain independent token state for different client keys. - Exercise 1.14, Fixed window: Use maps and structured values to track request counts associated with client keys and time windows.
These types form the foundation of the rate limiter's state. The next lessons will build on them with methods, interfaces, errors, testing, and concurrency.
References
Everything above is explained on this page; these are where it comes from (Go 1.2x).