Go Pointers to Struct

https://‮ww‬w.theitroad.com

In Go, pointers can be used to reference a struct. This allows you to modify the contents of the struct even if it is passed as a parameter to a function.

Here's an example of how to declare and use a pointer to a struct in Go:

type Person struct {
    name string
    age  int
}

func main() {
    // Declare a pointer to a Person struct
    var p *Person

    // Allocate memory for the struct and assign it to the pointer
    p = &Person{name: "John", age: 30}

    // Access the fields of the struct through the pointer
    fmt.Println((*p).name, (*p).age)

    // Alternatively, you can use the shorthand syntax to access fields through a pointer
    fmt.Println(p.name, p.age)

    // Pass the pointer to a function that modifies the struct
    modifyPerson(p)

    // Print the modified struct
    fmt.Println(p.name, p.age)
}

func modifyPerson(p *Person) {
    // Modify the fields of the struct through the pointer
    p.name = "Jane"
    p.age = 25
}

In this example, a struct Person is defined with two fields: name and age. A pointer to a Person struct is declared with var p *Person, and memory is allocated for the struct and assigned to the pointer with p = &Person{name: "John", age: 30}.

The modifyPerson function accepts a pointer to a Person struct and modifies the values of the name and age fields.

In the main function, the fields of the struct are accessed through the pointer using the (*p).name and (*p).age syntax, or the shorthand syntax p.name and p.age. The modifyPerson function is then called with the pointer, and the modified values are printed to the console.