create a pointer to a struct in go

To create a pointer to a struct in Go, you can use the & operator followed by the struct variable name. Here's an example:

main.go
type Person struct {
    Name string
    Age  int
}

func main() {
    // Creating a struct variable and assigning values
    p := Person{Name: "Alice", Age: 18}

    // Creating a pointer to the struct variable
    ptr := &p

    // Accessing struct fields using pointer
    fmt.Println(ptr.Name, ptr.Age) // Output: Alice 18
}
329 chars
16 lines

In this example, we first define a struct Person with two fields Name and Age. We then create a Person variable p and assign it some values.

Next, we create a pointer ptr to the struct variable p using the & operator. Finally, we can access the fields of the Person struct using the pointer ptr.

related categories

gistlibby LogSnag