0
0
Goprogramming~5 mins

Struct pointers in Go

Choose your learning style9 modes available
Introduction

Struct pointers let you work with the address of a struct instead of copying it. This helps save memory and lets you change the original struct easily.

When you want to update a struct inside a function and keep the changes after the function ends.
When you want to avoid copying large structs to save memory and improve speed.
When you want to share the same struct data between different parts of your program.
When you want to pass structs efficiently to functions or methods.
Syntax
Go
type StructName struct {
    Field1 type1
    Field2 type2
}

var ptr *StructName = &StructName{Field1: value1, Field2: value2}

The *StructName means a pointer to a struct of type StructName.

The & operator gets the address of a struct value.

Examples
Create a struct Person, then make a pointer pPtr to it.
Go
type Person struct {
    Name string
    Age  int
}

var p = Person{Name: "Alice", Age: 30}
var pPtr *Person = &p
Change the Age field through the pointer. This updates the original struct.
Go
pPtr.Age = 31
Function takes a pointer to Person and updates the age directly.
Go
func updateAge(p *Person, newAge int) {
    p.Age = newAge
}
Sample Program

This program shows how to use a struct pointer to update the original struct inside a function.

Go
package main

import "fmt"

type Person struct {
    Name string
    Age  int
}

func updateAge(p *Person, newAge int) {
    p.Age = newAge
}

func main() {
    p := Person{Name: "Bob", Age: 25}
    fmt.Println("Before update:", p)

    updateAge(&p, 26)

    fmt.Println("After update:", p)
}
OutputSuccess
Important Notes

Using pointers avoids copying the whole struct, which is faster for big structs.

Access struct fields through pointers using the dot . operator directly; Go handles the pointer dereference automatically.

Summary

Struct pointers hold the address of a struct, not a copy.

They let you change the original struct from functions or other parts of your code.

Use & to get a pointer and pass it to functions for efficient updates.