0
0
GoHow-ToBeginner · 3 min read

How to Use Pointer with Struct in Go: Simple Guide

In Go, you use a pointer to a struct by declaring a variable with *StructType and using the & operator to get the address of a struct instance. You can then access or modify the struct fields through the pointer using dot notation directly (e.g., ptr.field).
📐

Syntax

To use a pointer with a struct in Go, you declare a pointer variable with *StructType. Use the & operator to get the address of a struct instance. Access fields through the pointer using dot notation directly, as Go automatically dereferences pointers.

go
type Person struct {
    Name string
    Age  int
}

var p Person          // normal struct variable
var ptr *Person       // pointer to Person struct

p = Person{Name: "Alice", Age: 30}
ptr = &p             // ptr points to p

// Access fields via pointer
fmt.Println(ptr.Name) // prints "Alice"
ptr.Age = 31         // modifies p.Age through pointer
💻

Example

This example shows how to create a struct, get its pointer, and modify its fields through the pointer.

go
package main

import "fmt"

type Person struct {
    Name string
    Age  int
}

func main() {
    p := Person{Name: "Bob", Age: 25}
    ptr := &p

    fmt.Println("Before:", p)

    ptr.Age = 26 // change Age via pointer
    ptr.Name = "Robert" // change Name via pointer

    fmt.Println("After:", p)
}
Output
Before: {Bob 25} After: {Robert 26}
⚠️

Common Pitfalls

One common mistake is trying to use a pointer without initializing it, which causes a nil pointer error. Another is forgetting that Go automatically dereferences pointers when accessing fields, so you don't need to use *ptr explicitly to access fields.

go
package main

import "fmt"

type Person struct {
    Name string
}

func main() {
    var ptr *Person
    // fmt.Println(ptr.Name) // This will panic: runtime error: invalid memory address or nil pointer dereference

    p := Person{Name: "Eve"}
    ptr = &p
    fmt.Println(ptr.Name) // Correct usage
}
Output
Eve
📊

Quick Reference

ConceptSyntax/UsageNotes
Declare structtype Person struct { Name string; Age int }Defines a struct type
Declare pointervar ptr *PersonPointer to struct type
Get pointerptr = &pUse & to get address of struct variable
Access fieldptr.NameGo auto-dereferences pointer
Modify fieldptr.Age = 30Changes original struct data

Key Takeaways

Use & to get a pointer to a struct instance in Go.
Access and modify struct fields through the pointer using dot notation directly.
Avoid nil pointers by always initializing your pointer before use.
Go automatically dereferences pointers when accessing struct fields.
Pointers allow efficient updates to structs without copying data.