Challenge 2 - Data structure
- Go course
- Beginner
- Lesson 88/90
- 8 min
Write a contacts app with struct and slice.
Challenge: a library
Using structs, slices and append, you will write a small library manager. The Kitaplik type keeps books in a slice; Ekle(title string, pages int) adds a new book, and Uzunlar(min int) []string returns the titles of books with at least min pages.
var k Kitaplik
k.Ekle("Dune", 412)
k.Ekle("Simyacı", 184)
k.Ekle("Vakıf", 255)
fmt.Println(k.Uzunlar(250)) // [Dune Vakıf]Plan
1) type Kitap struct { Title string; Sayfa int }. 2) type Kitaplik struct { kitaplar []Kitap }. 3) func (k *Kitaplik) Ekle(...): k.kitaplar = append(k.kitaplar, Kitap{...}). 4) Uzunlar: create an empty []string, walk the books, append the titles that meet the condition and return it.
Practice Library manager
Write Kitap, Kitaplik, Ekle and Uzunlar following the plan. Add the three books and print the result of k.Uzunlar(250).
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
type Kitap struct {
Title string
Sayfa int
}
type Kitaplik struct {
kitaplar []Kitap
}
func (k *Kitaplik) Ekle(title string, sayfa int) {
k.kitaplar = append(k.kitaplar, Kitap{title, sayfa})
}
func (k *Kitaplik) Uzunlar(min int) []string {
var sonuc []string
for _, b := range k.kitaplar {
if b.Sayfa >= min {
sonuc = append(sonuc, b.Title)
}
}
return sonuc
}
func main() {
var k Kitaplik
k.Ekle("Dune", 412)
k.Ekle("Simyacı", 184)
k.Ekle("Vakıf", 255)
fmt.Println(k.Uzunlar(250))
}Expected output
[Dune Vakıf]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which receivers should <code>Ekle</code> and <code>Uzunlar</code> use?
- Both value receivers
- Both should be functions
- It doesn't matter
- Ekle *Kitaplik (it changes), Uzunlar Kitaplik or *Kitaplik (it reads) Correct answer
Explanation: Ekle grows the slice, so a pointer receiver is required; for consistency usually all are written with pointer receivers.
2 Add a book
func (k *Kitaplik) Ekle(title string, sayfa int) {
k.kitaplar = ____(k.kitaplar, Kitap{title, sayfa})
}
func (k *Kitaplik) Ekle(title string, sayfa int) {
k.kitaplar = append(k.kitaplar, Kitap{title, sayfa})
}
Explanation: append adds the new book to the slice; the result is assigned back to the field.
3 Part and role
| Term | Meaning |
|---|---|
Kitap |
A single record |
Kitaplik |
A record collection |
Ekle |
Grows with append |
Uzunlar |
Filters |