Home »
Golang
Go Access Struct Members
Last Updated : July 22, 2025
In Go, struct members (also called fields) are accessed using the dot (.
) operator. Once a struct variable is created, you can read or modify its fields using this syntax.
Accessing Struct Members
To access a field in a struct, use the dot notation: structVariable.fieldName
.
Example
The following example demonstrates how to create a struct and access its fields:
package main
import "fmt"
type Book struct {
title string
author string
pages int
}
func main() {
b := Book{"Learning Go", "Ravi Kumar", 300}
fmt.Println("Title:", b.title)
fmt.Println("Author:", b.author)
fmt.Println("Pages:", b.pages)
}
When you run the above code, the output will be:
Title: Learning Go
Author: Ravi Kumar
Pages: 300
Explanation
b
is an instance of the Book
struct.
- Each field (
title
, author
, pages
) is accessed using dot notation.
Modifying Struct Members
You can also modify struct fields after the struct variable is declared using the same dot notation.
Example
The following example demonstrates how to declare a structure, assign values to its fields individually, and print the updated structure:
package main
import "fmt"
type Book struct {
title string
author string
pages int
}
func main() {
var b Book
b.title = "Mastering Go"
b.author = "Anjali Sharma"
b.pages = 250
fmt.Println("Updated Book:", b)
}
When you run the above code, the output will be:
Updated Book: {Mastering Go Anjali Sharma 250}
Accessing Struct Members via Pointer
If you have a pointer to a struct, you can still access its members directly using the dot notation. Go automatically dereferences the pointer.
Example
The following example demonstrates how to access structure fields using a pointer in Go, where the dot operator automatically dereferences the pointer:
package main
import "fmt"
type Book struct {
title string
pages int
}
func main() {
b := Book{"Go in Action", 320}
p := &b
fmt.Println("Title:", p.title)
fmt.Println("Pages:", p.pages)
}
When you run the above code, the output will be:
Title: Go in Action
Pages: 320
Key Points
- Struct fields are accessed using the dot (
.
) operator.
- You can both read and modify struct fields using dot notation.
- Pointer to struct still allows dot notation to access fields due to Go’s automatic dereferencing.
Go Access Struct Members Exercise
Select the correct option to complete each statement about accessing struct members in Go.
- To access a field in a struct in Go, use:
- Which of the following allows you to modify a struct field?
- When using a pointer to a struct, how do you access a field?
Advertisement
Advertisement