Field access
- Go course
- Beginner
- Lesson 71/90
- 4 min
Learn to access struct fields with the dot operator.
Field access
Fields are read and written with a dot. If the struct is in a slice, an element's field is changed through the index:
kitaplar := []Kitap{{"Dune", "Herbert", 412}, {"Vakıf", "Asimov", 255}}
kitaplar[1].Sayfa = 300
for _, k := range kitaplar {
fmt.Println(k.Title, k.Sayfa)
}The k in a for _, k := range loop is a copy; k.Sayfa = ... doesn't change the slice.
Struct tags
A tag can be written in backticks after a field; libraries read these tags. The most common are JSON field names:
type Kitap struct {
Title string `json:"title"`
Sayfa int `json:"sayfa,omitempty"`
}Tags don't change how Go code behaves; only packages that read them through reflection (encoding/json, database libraries) use them.
Practice Bulk update
Define the Kitap struct (Title string, Sayfa int). Increase every book's pages by 10 through the index in a two-book slice and print the total page count (starting values: 412 and 255).
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
type Kitap struct {
Title string
Sayfa int
}
func main() {
kitaplar := []Kitap{{"Dune", 412}, {"Vakıf", 255}}
for i := range kitaplar {
kitaplar[i].Sayfa += 10
}
toplam := 0
for _, k := range kitaplar {
toplam += k.Sayfa
}
fmt.Println(toplam)
}Expected output
687
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which correctly increases every book's page count by 10?
- kitaplar.Sayfa += 10
- It isn't possible
- for i := range kitaplar { kitaplar[i].Sayfa += 10 } Correct answer
- for _, k := range kitaplar { k.Sayfa += 10 }
Explanation: The change must go through the index; the value range gives is a copy of the element.
2 Change by index
for i := range kitaplar {
kitaplar____.Sayfa += 10
}
for i := range kitaplar {
kitaplar[i].Sayfa += 10
}
Explanation: kitaplar[i] reaches the real element in the slice.
3 Expression and effect
| Term | Meaning |
|---|---|
k.Title |
Reads the field |
kitaplar[1].Sayfa = 300 |
Changes the element in the slice |
for _, k := range |
Gives a copy |
`json:"title"` |
A tag |