Summary - Struct
- Go course
- Beginner
- Lesson 74/90
- 4 min
Combine struct, embedding and pointer to write a person record.
Structs summary
Structs are Go's data model: defined with type Name struct { ... }, created with named fields, copied on assignment, and supporting == when their fields are comparable. They are shared and changed through pointers (&T{}, p.Field). Embedding promotes the fields of other structs; tags give information to libraries.
Working on a slice of structs
In real programs structs are mostly kept in slices and filtered:
var uzun []Kitap
for _, k := range kitaplar {
if k.Sayfa > 300 {
uzun = append(uzun, k)
}
}slices.SortFunc(kitaplar, func(a, b Kitap) int { return a.Sayfa - b.Sayfa }) sorts a struct slice by a field.
Practice Sorted books
Create a Kitap (Title string, Sayfa int) slice with {"Dune", 412}, {"Simyacı", 184}, {"Vakıf", 255}. Sort it by pages ascending with slices.SortFunc and print the titles in order on one line.
Starter code
package main
import (
"fmt"
"slices"
)
func main() {
// buraya yaz
}Sample solution
package main
import (
"fmt"
"slices"
)
type Kitap struct {
Title string
Sayfa int
}
func main() {
kitaplar := []Kitap{{"Dune", 412}, {"Simyacı", 184}, {"Vakıf", 255}}
slices.SortFunc(kitaplar, func(a, b Kitap) int { return a.Sayfa - b.Sayfa })
for _, k := range kitaplar {
fmt.Print(k.Title, " ")
}
fmt.Println()
}Expected output
Simyacı Vakıf Dune
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What do you see when printing a struct with <code>fmt.Printf("%+v", k)</code>?
- Only the values
- A memory address
- JSON
- Values with field names: {Title:Dune Sayfa:412} Correct answer
Explanation: %v shows only the values, %+v also the field names, and %#v the Go syntax.
2 Print with fields
fmt.Printf("____
", Kitap{"Dune", 412}) // {Title:Dune Sayfa:412}
fmt.Printf("%+v
", Kitap{"Dune", 412}) // {Title:Dune Sayfa:412}
Explanation: %+v prints the struct together with its field names.
3 Group summary
| Term | Meaning |
|---|---|
type T struct |
Definition |
T{Alan: x} |
Named creation |
Embedding |
Composition |
p.Alan |
Automatic dereference |