Home »
Golang
Go Pointer to a Struct
Last Updated : July 17, 2025
In Go, you can create a pointer to a struct to access or modify its fields without copying the entire struct.
Creating a Pointer to a Struct
You can create a pointer to a struct using the address-of operator & or by using the new function.
Example: Using & operator
The following example demonstrates how to access struct fields using a pointer without explicit dereferencing in Go:
package main
import "fmt"
type Book struct {
title string
author string
}
func main() {
b := Book{title: "Go Basics", author: "Vishnu"}
ptr := &b
fmt.Println("Title:", ptr.title)
fmt.Println("Author:", ptr.author)
}
When executed, this program outputs:
Title: Go Basics
Author: Vishnu
You can access struct fields directly using the pointer without explicitly dereferencing.
Example: Using new()
The following example demonstrates how to create a pointer to a struct using the new function and access its fields in Go:
package main
import "fmt"
type Book struct {
title string
}
func main() {
ptr := new(Book)
ptr.title = "Learning Go"
fmt.Println("Book title:", ptr.title)
}
Output:
Book title: Learning Go
Modifying Struct Fields via Pointer
You can modify struct fields via a pointer, and the changes will affect the original struct.
Example
The following example demonstrates how to modify a struct's field by passing a pointer to the struct into a function in Go:
package main
import "fmt"
type Student struct {
name string
age int
}
func updateAge(s *Student, newAge int) {
s.age = newAge
}
func main() {
st := Student{name: "Neha", age: 20}
updateAge(&st, 25)
fmt.Println("Updated Age:", st.age)
}
When executed, this program outputs:
Updated Age: 25
Function Returning Pointer to Struct
Functions can return a pointer to a struct. This allows dynamic creation and initialization.
Example
The following example demonstrates how to return a pointer to a struct from a function in Go:
package main
import "fmt"
type Car struct {
brand string
year int
}
func newCar(brand string, year int) *Car {
return &Car{brand: brand, year: year}
}
func main() {
c := newCar("BMW", 2022)
fmt.Println("Car:", c.brand, "-", c.year)
}
Output:
Car: BMW - 2022
Nil Pointer to Struct
A pointer to a struct can be nil. You must check for nil before accessing fields to avoid runtime errors.
Example
The following example demonstrates how to safely handle nil pointers when working with structs:
package main
import "fmt"
type Employee struct {
name string
}
func printName(e *Employee) {
if e == nil {
fmt.Println("Invalid employee")
return
}
fmt.Println("Employee name:", e.name)
}
func main() {
var emp *Employee
printName(emp)
}
Output:
Invalid employee
Exercise
Choose the correct answers to test your understanding of pointers to structs in Go.
- How do you create a pointer to a struct value
p?
- Which keyword can be used to allocate and return a pointer to a struct?
- How do you access a field in a struct pointer
ptr?
Advertisement
Advertisement