![]() |
VOOZH | about |
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.
Using pointers with structs is helpful when:
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.
There are two common ways to create a pointer to a struct in Go:
& operator to get the memory address of an existing struct.new function, which returns a pointer to a newly allocated struct.& operatorIn this approach, we use the & operator to get the address of an existing struct.
Example:
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.
new functionThe new function can also be used to create a pointer to a struct. This function allocates memory and returns a pointer to the struct.
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.
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.