CodeBlanks Logo Icon CodeBlanks

Computing total

Compute the cart total with range.

Computing the total

The cart total is the sum of every product's subtotal. Walk the products with range and accumulate:

func (s Sepet) Toplam() float64 {
    t := 0.0
    for _, u := range s.Urunler {
        t += u.AraToplam()
    }
    return t
}

A value receiver is enough here because the cart is only read.

A discount rule

Business rules are added as methods too. For example, a 10% discount on purchases over 100 TL:

func (s Sepet) Odenecek() float64 {
    t := s.Toplam()
    if t > 100 {
        return t * 0.9
    }
    return t
}

Keeping the rule in a separate method means only one place changes when the rule does.

Practice Total and discount

Write Urun (with AraToplam), Sepet, and the Toplam and Odenecek methods. The cart holds Kalem 12.5 × 5 and Çanta 80 × 1; print the total and the amount due on one line.

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
}

func (u Urun) AraToplam() float64 { return u.Fiyat * float64(u.Adet) }

type Sepet struct{ Urunler []Urun }

func (s Sepet) Toplam() float64 {
    t := 0.0
    for _, u := range s.Urunler {
        t += u.AraToplam()
    }
    return t
}

func (s Sepet) Odenecek() float64 {
    t := s.Toplam()
    if t > 100 {
        return t * 0.9
    }
    return t
}

func main() {
    s := Sepet{Urunler: []Urun{{"Kalem", 12.5, 5}, {"Çanta", 80, 1}}}
    fmt.Println(s.Toplam(), s.Odenecek())
}

Expected output

142.5 128.25

Questions and answers

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

1 What happens if <code>t := 0</code> is written instead of <code>t := 0.0</code>?

  • The result is rounded
  • t becomes nil
  • t becomes an int and t += float64 is a compile error Correct answer
  • It makes no difference

Explanation: := infers the type from the value; 0 gives int, 0.0 gives float64. Go doesn't mix int and float64.

2 Accumulate

Question
for _, u := range s.Urunler {
    t ____ u.AraToplam()
}
Answer
for _, u := range s.Urunler {
    t += u.AraToplam()
}

Explanation: t += x adds x to t and writes the result back to t.

3 Cart and result

Term Meaning
Kalem 12.5 × 5 62.5
Defter 20 × 1 20
Toplam 82.5
Toplam > 100 10% discount

All lessons in Beginner