Understand the contract

A struct groups fields into a single value with a defined type. Use one when several values describe the same thing, such as a task’s title and completion state. Named fields make construction readable and allow different types within the same record without relying on positional conventions.

Fields beginning with an uppercase letter are exported outside the package. A struct literal can initialize selected fields; omitted fields receive their zero values. Access fields with a dot. You can add methods to a named struct type later without changing the basic representation.

Work through the example

The example constructs a task whose Done field defaults to false. Assigning it to completed copies the struct, so setting completed.Done leaves task.Done unchanged. The resulting values share their title text safely because strings are immutable, while their boolean fields are independent.

package main

import "fmt"

type Task struct {
    Title string
    Done  bool
}

func main() {
    task := Task{Title: "Learn Go"}
    completed := task
    completed.Done = true
    fmt.Println(task, completed)
}

Watch this boundary

Struct copying is shallow with respect to fields that refer to other storage. If Task contains a slice of labels, copying Task also copies the slice descriptor and can leave labels shared. Decide whether your API returns snapshots or shared data, and copy nested collections when independence is required.

Practice with a changed input

Add a []string field named Labels, copy the task and modify one label through the copy. Explain why its behavior differs from the Done field.

References & further reading

Need help with your Go backend?

I work with engineering teams on focused Go and Kubernetes platform engagements, with limited consulting availability.

Explore Go consulting services