Pointer to a Struct in Golang (original) (raw)

Last Updated : 12 Jul, 2025

In Go, structs are used to create custom data types that group different fields together. When working with structs, using pointers can be especially beneficial for managing memory efficiently and for avoiding unnecessary copying of data. A pointer to a struct allows you to directly reference and modify the data in the original struct without making a copy.

Why Use Pointers with Structs?

Using pointers with structs is helpful when:

Struct Example

package main
import "fmt"

// Defining a struct
type Person struct {
name string
age int
}

func main() {
// Creating an instance of the struct
p1 := Person{name: "A", age: 25}

fmt.Println("Original struct:", p1)  

}

In this example, we define a Person struct with fields name and age. The variable p1 is an instance of this struct.

Declaring a Pointer to a Struct

There are two common ways to create a pointer to a struct in Go:

  1. **Using the & operator to get the memory address of an existing struct.
  2. **Using the new function, which returns a pointer to a newly allocated struct.

Table of Content

**Using the & operator

In this approach, we use the & operator to get the address of an existing struct.

**Example:

Go `

package main import "fmt"

// Defining a struct type Person struct { name string age int }

func main() { // Creating an instance of the struct p1 := Person{name: "A", age: 25}

// Creating a pointer to the struct
personPointer := &p1

// Accessing fields using the pointer
fmt.Println("Name:", personPointer.name) // Automatically dereferences
fmt.Println("Age:", personPointer.age)

// Modifying struct values using the pointer
personPointer.age = 26
fmt.Println("Updated struct:", p1)

}

`

Output

Name: A Age: 25 Updated struct: {A 26}

Here, personPointer := &p1 assigns a pointer to the p1 struct. When we modify personPointer.age, it directly updates p1 because they refer to the same memory address.

**Using the new function

The new function can also be used to create a pointer to a struct. This function allocates memory and returns a pointer to the struct.

Go `

package main import "fmt"

// Defining a struct type Person struct { name string age int }

func main() { // Creating a pointer to a new instance of Person personPointer := new(Person) personPointer.name = "B" personPointer.age = 30

fmt.Println("Struct created with new:", *personPointer)

}

`

Output

Struct created with new: {B 30}

Using new(Person) creates a pointer to an empty Person struct (personPointer). We then set the fields of this struct through the pointer.

Accessing Struct Fields Through a Pointer

In Go, we don’t need to explicitly dereference the pointer (**using *) to access the fields. Go automatically dereferences pointers when accessing fields, so personPointer.name works directly without ( *personPointer).name.