ProgramGuru

Accessing Struct Fields

Start with Accessing Struct Fields

Use the dot operator to read and write an individual field of a struct value.

What you’ll learn

  • Explain the main purpose of accessing struct fields.
  • Read and run the complete Go example in this lesson.
  • Apply the concept and recognize common mistakes.

Understand the idea

For item.Price, the selector names a field in item. With a pointer to a struct, Go also allows pointer.Price rather than requiring (*pointer).Price.

Exported fields start with an uppercase letter, which matters when using a struct from another package. Within the same package, unexported fields are accessible too.

Visualize how it works

Follow this diagram before executing the example. Check where a value or decision changes what runs next.

Visual explanation for struct fieldsThe dot selector works through a valid struct pointer.item.Price = 10Step 1ptr := &itemStep 2ptr.Price = 15Step 3item.Price == 15Step 4The dot selector works through a valid struct pointer.
The dot selector works through a valid struct pointer.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import "fmt"

type Product struct {
	Name  string
	Price int
}

func main() {
	item := Product{Name: "Pen", Price: 10}
	fmt.Println("Before:", item.Price)
	ptr := &item
	ptr.Price = 15
	fmt.Println("Name:", item.Name)
	fmt.Println("After:", item.Price)
}

Output

Before: 10
Name: Pen
After: 15

Trace what the program does

Reading item.Price returns 10. The pointer selector ptr.Price accesses the same field through a pointer, changing it to 15. The original item reflects that update.

Avoid common mistakes

  • Selectors on a nil pointer to a struct cannot access an actual target field.
  • Field visibility across packages depends on whether the name is exported.

Try it yourself

Add a Stock field to Product, update it through a pointer and print the product after the change.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

What does ptr.Price do when ptr points to a Product?
Choose one answer. You can try again.

Answer and explanation

Accesses Price on the target struct

Correct. Reading item.

What you should remember

You have practiced Accessing Struct Fields in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Nested Structs →