CodeBlanks Logo Icon CodeBlanks

Adding to cart

Add products to the cart with append.

Adding to the cart

The cart is a slice of products. Adding is done with append. If the same product is added a second time, its quantity should increase instead of adding a new row; so the cart is searched first:

type Sepet struct{ Urunler []Urun }

func (s *Sepet) Ekle(u Urun) {
    for i := range s.Urunler {
        if s.Urunler[i].Ad == u.Ad {
            s.Urunler[i].Adet += u.Adet
            return
        }
    }
    s.Urunler = append(s.Urunler, u)
}

Changing with for i := range

Using for _, u := range s.Urunler while increasing the quantity doesn't work: u is a copy and the change doesn't reach the slice. That's why we iterate by index and change it through s.Urunler[i].Adet. This is one of the most common mistakes for Go beginners.

Practice The Ekle method

Write Urun, Sepet and the Ekle method. Add Kalem (3), Defter (1) and Kalem again (2) to the cart. Print the number of products and the pen's quantity.

Starter code

main.go
package main

import "fmt"

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import "fmt"

type Urun struct {
    Ad    string
    Fiyat float64
    Adet  int
}

type Sepet struct{ Urunler []Urun }

func (s *Sepet) Ekle(u Urun) {
    for i := range s.Urunler {
        if s.Urunler[i].Ad == u.Ad {
            s.Urunler[i].Adet += u.Adet
            return
        }
    }
    s.Urunler = append(s.Urunler, u)
}

func main() {
    var s Sepet
    s.Ekle(Urun{"Kalem", 12.5, 3})
    s.Ekle(Urun{"Defter", 20, 1})
    s.Ekle(Urun{"Kalem", 12.5, 2})
    fmt.Println(len(s.Urunler), s.Urunler[0].Adet)
}

Expected output

2 5

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Why does <code>Ekle</code> use a pointer receiver (<code>*Sepet</code>)?

  • Because it is shorter
  • Because slices require pointers
  • It isn't required
  • To change the cart itself; a value receiver would work on a copy Correct answer

Explanation: append returns a new slice header; writing it back to the Sepet permanently requires a pointer receiver.

2 Append to the end

Question
s.Urunler = ____(s.Urunler, u)
Answer
s.Urunler = append(s.Urunler, u)

Explanation: append adds the new product to the end of the slice; the result is assigned back to the field.

3 Case and behavior

Term Meaning
New product Added with append
Existing product Quantity increases
for _, u := range A copy, doesn't work
*Sepet Lasting change

All lessons in Beginner