AzLearn

تمرين إعادة البناء

CSV Expense Summarizer

أعد كتابة برنامج Go يلخص مصروفات من CSV.

go ~16 دقيقة مبتدئ
أعد بناء الكود Rebuild

هذا هو الكود. اكتبه بنفسك.

الكود المرجعي
package main

import (
	"encoding/csv"
	"fmt"
	"io"
	"os"
	"strconv"
	"strings"
)

func summarizeExpenses(reader io.Reader) (map[string]int, error) {
	rows, err := csv.NewReader(reader).ReadAll()
	if err != nil {
		return nil, err
	}

	totals := make(map[string]int)
	for index, row := range rows {
		if index == 0 {
			continue
		}
		halalas, err := strconv.Atoi(row[2])
		if err != nil {
			return nil, err
		}
		totals[row[1]] += halalas
	}

	return totals, nil
}

func main() {
	csvText := `date,category,halalas
2026-04-01,books,4500
2026-04-02,coffee,1800
2026-04-03,books,2500
`

	totals, err := summarizeExpenses(strings.NewReader(csvText))
	if err != nil {
		fmt.Println("error:", err)
		os.Exit(1)
	}

	for category, halalas := range totals {
		fmt.Printf("%-8s %6.2f SAR\n", category, float64(halalas)/100)
	}
}
اكتب هنا