← Back to Go Course | Chapter 6: Structs & Methods | Lesson 1 of 6

Structs

A struct is like a form with several labeled blanks -- one shape can hold a name, an age, and an address all bundled together as one thing.

Defining a Struct

A struct type is declared with 'type Name struct { }', listing each field's name and type. It's Go's way of bundling several related pieces of data into one custom type.

Example: Defining a Struct

markup
package main

import "fmt"

type Person struct {
	Name string
	Age  int
}

func main() {
	p := Person{Name: "Asha", Age: 32}
	fmt.Println(p.Name, p.Age)
}

Struct Literals

A struct value can be created with a literal listing values for named fields (in any order), or with positional values matching the exact declaration order -- named fields are strongly preferred for readability and safety.

Note: Prefer named fields in struct literals -- they're self-documenting and survive field reordering.

Example: Struct Literals

markup
package main

import "fmt"

type Point struct {
	X, Y int
}

func main() {
	a := Point{X: 3, Y: 4}
	b := Point{5, 6} // positional: X=5, Y=6
	fmt.Println(a, b)
}

Modifying Struct Fields

Once you have a struct value, its fields are accessed and modified with dot notation, just like accessing a property on an object in most other languages.

Example: Modifying Struct Fields

markup
package main

import "fmt"

type Counter struct {
	Value int
}

func main() {
	c := Counter{Value: 0}
	c.Value = c.Value + 1
	c.Value++
	fmt.Println(c.Value)
}

Comparing Structs

Two struct values of the same type can be compared with == as long as every field is itself comparable -- the comparison checks that all fields are equal, not just that they're the same object in memory.

Example: Comparing Structs

markup
package main

import "fmt"

type Point struct {
	X, Y int
}

func main() {
	a := Point{1, 2}
	b := Point{1, 2}
	fmt.Println("equal:", a == b)
}
Common Mistakes
  1. Forgetting struct field names must be capitalized to be accessible from other packages (exported), not just for style.
  2. Comparing two structs with == when one of their fields is a non-comparable type like a slice or map, which fails to compile.
  3. Creating a struct literal with positional values and getting the field order wrong, instead of using named fields for clarity.
Chapter Summary
  • A struct groups related fields together into a single named type.
  • Struct literals can use named fields (recommended) or positional values matching declaration order.
  • Structs are compared field by field with ==, as long as every field type is itself comparable.
  • Structs are the foundation Go uses instead of classes for grouping data.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.