How to Use Struct with Pointer in Go: Syntax and Examples
In Go, you use a
struct pointer by declaring a variable with *StructType and using the & operator to get the address of a struct instance. Access struct fields through the pointer using the dot notation, as Go automatically dereferences pointers to structs.Syntax
To use a pointer to a struct in Go, declare a variable with *StructType. Use the & operator to get the pointer to a struct instance. Access fields with the dot . operator directly on the pointer.
- StructType: The name of your struct.
- *StructType: Pointer to the struct.
- &: Gets the memory address of a struct instance.
- Pointer.field: Accesses the field; Go dereferences automatically.
go
type Person struct { Name string Age int } var p *Person // Pointer to Person struct p = &Person{Name: "Alice", Age: 30} // Get pointer to struct instance fmt.Println(p.Name) // Access field via pointer
Example
This example shows how to create a struct, get its pointer, modify fields through the pointer, and print the results.
go
package main import "fmt" type Person struct { Name string Age int } func main() { p := Person{Name: "Bob", Age: 25} // Create struct instance ptr := &p // Get pointer to struct fmt.Println("Before:", ptr.Name, ptr.Age) // Access fields via pointer ptr.Age = 26 // Modify field through pointer fmt.Println("After:", ptr.Name, ptr.Age) }
Output
Before: Bob 25
After: Bob 26
Common Pitfalls
Common mistakes include trying to access fields with (*ptr).field instead of ptr.field, or forgetting to use & to get the pointer. Also, assigning a struct value to a pointer variable without using & causes errors.
Go automatically dereferences pointers to structs, so use ptr.field directly.
go
package main import "fmt" type Person struct { Name string } func main() { p := Person{Name: "Eve"} // Wrong: var ptr *Person = p // Cannot assign struct to pointer var ptr *Person = &p // Correct: get pointer with & // Wrong: fmt.Println((*ptr).Name) // Works but verbose fmt.Println(ptr.Name) // Preferred: Go auto-dereferences }
Output
Eve
Quick Reference
| Concept | Usage | Notes |
|---|---|---|
| Declare pointer | var p *Person | Pointer to struct type |
| Get pointer | p = &Person{Name: "Ann"} | Use & to get address |
| Access field | p.Name | Auto dereference pointer |
| Modify field | p.Age = 30 | Change value via pointer |
| Common error | var p *Person = Person{} | Must use & to assign pointer |
Key Takeaways
Use & to get a pointer to a struct instance in Go.
Access struct fields through pointers using dot notation; Go dereferences automatically.
Never assign a struct value directly to a pointer variable without &.
Modifying struct fields via pointer changes the original struct.
Avoid using *ptr.field; just use ptr.field for clarity and simplicity.