Go
Challenge 2 - Data structure
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.
Exercise Library manager
Write Kitap, Kitaplik, Ekle and Uzunlar following the plan. Add the three books and print the result of k.Uzunlar(250).
Show example 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))
}
Test yourself
-
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)
Show answer
Ekle *Kitaplik (it changes), Uzunlar Kitaplik or *Kitaplik (it reads) — Ekle grows the slice, so a pointer receiver is required; for consistency usually all are written with pointer receivers.
-
Add a book
func (k *Kitaplik) Ekle(title string, sayfa int) {
k.kitaplar = ____(k.kitaplar, Kitap{title, sayfa})
}
Show answer
func (k *Kitaplik) Ekle(title string, sayfa int) {
k.kitaplar = append(k.kitaplar, Kitap{title, sayfa})
}
-
Part and role
- Kitap
- A single record
- Kitaplik
- A record collection
- Ekle
- Grows with append
- Uzunlar
- Filters
Next lesson: Challenge 3 - Error handling