乐闻世界logo
搜索文章和话题

How to Create and Use Pointers to Structs in Go?

2月7日 11:07

In Go, creating and using pointers to structs involves several key steps:

  1. Define a struct: First, define a struct, which will be the type that your pointer points to.
go
type Person struct { Name string Age int }
  1. Create a pointer to a struct instance: You can create a pointer to a struct instance using the new keyword or the & operator.

    • Using the new keyword:

      go
      p := new(Person)

      Here, p is a pointer to the Person type, and the struct fields are initialized to zero values (i.e., strings are "" and integers are 0).

    • Using the & operator:

      go
      person := Person{Name: "Alice", Age: 30} p := &person

      Here, p is a pointer to the person instance.

  2. Access and modify fields of the struct pointed to by the pointer: You can directly access and modify the struct fields through the pointer, even using the dot operator (.).

go
p.Name = "Bob" p.Age = 25 fmt.Println(p.Name) // Output: "Bob" fmt.Println(p.Age) // Output: 25

This approach allows you to flexibly use pointers in Go to operate on struct instances and pass complex data structures through pointers without copying the entire struct, which is highly beneficial for improving program efficiency.

标签:Golang