Pointer to a Struct in Golang
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:
- You want to avoid copying large structs by passing references instead.
- You need to modify the original struct values from within a function.
- You want to improve performance by reducing memory usage.
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:
- Using the
&
operator to get the memory address of an existing struct. - Using the
new
function, which returns a pointer to a newly allocated struct.
Using the &
operator
In this approach, we use the &
operator to get the address of an existing 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}
// 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.
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
.