Pointer to a Struct in Golang

In Go, you can create a pointer to a struct in the same way you create a pointer to any other type. Pointers to structs are useful when you want to modify the struct’s fields directly, especially when dealing with larger data structures.

Here’s an example of creating and using a pointer to a struct:

package main

import "fmt"

type Person struct {
    FirstName string
    LastName  string
    Age       int
}

func main() {
    // Create a struct instance
    person := Person{
        FirstName: "John",
        LastName:  "Doe",
        Age:       30,
    }

    // Create a pointer to the struct
    personPtr := &person

    // Modify struct fields through the pointer
    personPtr.Age = 31

    // Access struct fields through the pointer
    fmt.Println("First Name:", personPtr.FirstName)
    fmt.Println("Last Name:", personPtr.LastName)
    fmt.Println("Age:", personPtr.Age)
}

Output :

First Name: John
Last Name: Doe
Age: 31

In this example, we define a Person struct with FirstName, LastName, and Age fields. We create an instance of the struct named person. Then, we create a pointer to the person instance using &person. We can modify and access the struct fields directly through the pointer.

Keep in mind that modifying fields through a pointer to a struct affects the original struct, making pointers a useful tool for modifying data in a shared manner.

Here’s another example that demonstrates using a pointer to a struct, along with a function that accepts a pointer to a struct as an argument:

package main

import "fmt"

type Student struct {
    Name  string
    Age   int
    Grade string
}

func updateStudent(s *Student, newName string, newAge int) {
    s.Name = newName
    s.Age = newAge
}

func main() {
    // Create a struct instance
    student := Student{
        Name:  "Alice",
        Age:   18,
        Grade: "A",
    }

    // Create a pointer to the struct
    studentPtr := &student

    fmt.Println("Before Update:")
    fmt.Println("Name:", studentPtr.Name)
    fmt.Println("Age:", studentPtr.Age)
    fmt.Println("Grade:", studentPtr.Grade)

    // Call function to update struct fields
    updateStudent(studentPtr, "Bob", 19)

    fmt.Println("\nAfter Update:")
    fmt.Println("Name:", studentPtr.Name)
    fmt.Println("Age:", studentPtr.Age)
    fmt.Println("Grade:", studentPtr.Grade)
}

Output :

Before Update:
Name: Alice
Age: 18
Grade: A

After Update:
Name: Bob
Age: 19
Grade: A

In this example, we define a Student struct and a function updateStudent that takes a pointer to a Student struct as an argument. Inside the function, we modify the fields of the struct using the pointer. In the main function, we create a Student instance, create a pointer to it, and then pass the pointer to the updateStudent function to modify its fields. As you can see, the changes made inside the function are reflected outside as well.