How to Access Struct Fields in Go: Simple Guide
In Go, you access struct fields using the dot operator
. after the struct variable name, like structVar.fieldName. For pointer to struct, use pointerVar.fieldName directly, as Go automatically dereferences pointers when accessing fields.Syntax
To access a field of a struct, use the dot operator . after the struct variable name followed by the field name.
If you have a pointer to a struct, you can access the field directly with the dot operator; Go handles the pointer dereference automatically.
go
type Person struct { Name string Age int } var p Person p.Name = "Alice" // Access field 'Name' var ptr *Person = &p ptr.Age = 30 // Access field 'Age' via pointer
Example
This example shows how to define a struct, create an instance, and access its fields both directly and through a pointer.
go
package main import "fmt" type Person struct { Name string Age int } func main() { p := Person{Name: "Bob", Age: 25} fmt.Println("Name:", p.Name) // Access field directly fmt.Println("Age:", p.Age) ptr := &p ptr.Name = "Charlie" // Access field via pointer ptr.Age = 28 fmt.Println("Updated Name:", p.Name) fmt.Println("Updated Age:", p.Age) }
Output
Name: Bob
Age: 25
Updated Name: Charlie
Updated Age: 28
Common Pitfalls
One common mistake is trying to access struct fields through a nil pointer, which causes a runtime panic.
Another is forgetting that unexported fields (starting with lowercase) cannot be accessed from other packages.
go
package main import "fmt" type Person struct { name string // unexported field Age int } func main() { var ptr *Person // fmt.Println(ptr.Age) // This will panic: dereference of nil pointer p := Person{name: "Dave", Age: 40} // fmt.Println(p.name) // Cannot access unexported field from outside package fmt.Println(p.Age) // This works }
Quick Reference
- Use
structVar.fieldNameto access fields. - Use
pointerVar.fieldNamefor pointers; Go dereferences automatically. - Unexported fields (lowercase) are private to the package.
- Accessing fields via nil pointers causes runtime errors.
Key Takeaways
Access struct fields using the dot operator after the struct variable name.
Go automatically dereferences pointers when accessing struct fields via pointers.
Unexported fields (starting with lowercase) cannot be accessed outside their package.
Avoid accessing fields through nil pointers to prevent runtime panics.
Use pointers to structs when you want to modify the original struct data.