0
0
Goprogramming~5 mins

Accessing struct fields in Go

Choose your learning style9 modes available
Introduction

Structs group related data together. Accessing struct fields lets you get or change specific pieces of that data.

You want to store information about a person, like name and age, and then read or update those details.
You have a product with price and quantity, and you need to calculate total cost using those fields.
You want to organize settings for a game or app and access each setting separately.
You receive data from a sensor and want to read specific measurements stored in a struct.
Syntax
Go
structVariable.fieldName

Use the dot . to get or set a field inside a struct variable.

Field names start with a capital letter if you want to access them from other packages.

Examples
Set and print fields of a struct variable.
Go
type Person struct {
    Name string
    Age  int
}

var p Person
p.Name = "Alice"
p.Age = 30
fmt.Println(p.Name, p.Age)
Create a struct with values and access fields to print them.
Go
p := Person{Name: "Bob", Age: 25}
fmt.Println(p.Name)
fmt.Println(p.Age)
Change one field after creating the struct.
Go
type Point struct {
    X, Y int
}

pt := Point{X: 10, Y: 20}
pt.X = 15
fmt.Println(pt.X, pt.Y)
Sample Program

This program creates a Car struct, prints its fields, updates the Year field, and prints it again.

Go
package main

import "fmt"

type Car struct {
    Brand string
    Year  int
}

func main() {
    myCar := Car{Brand: "Toyota", Year: 2020}
    fmt.Println("Brand:", myCar.Brand)
    fmt.Println("Year:", myCar.Year)

    // Update the year
    myCar.Year = 2022
    fmt.Println("Updated Year:", myCar.Year)
}
OutputSuccess
Important Notes

If you have a pointer to a struct, you can access fields with the same dot syntax, Go handles the pointer automatically.

Trying to access a field that does not exist will cause a compile error.

Summary

Use structVariable.fieldName to access or change a struct's field.

Fields hold the data inside a struct and can be read or updated.

Structs help organize related data in one place.