feat: 添加商品数据结构和计算功能
- 创建 Product 和 ProductGroup 类型定义- 实现商品列表初始化及分类逻辑 - 添加价格转换为货币格式的功能 - 实现按类别计算子总额与总金额功能 - 创建主函数调用并展示总额计算结果
This commit is contained in:
3
14-concurrency/concurrency/go.mod
Normal file
3
14-concurrency/concurrency/go.mod
Normal file
@@ -0,0 +1,3 @@
|
||||
module concurrency
|
||||
|
||||
go 1.22
|
||||
9
14-concurrency/concurrency/main.go
Normal file
9
14-concurrency/concurrency/main.go
Normal file
@@ -0,0 +1,9 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
func main() {
|
||||
fmt.Println("main function started")
|
||||
CalcStoreTotal(Products)
|
||||
fmt.Println("main function complete")
|
||||
}
|
||||
19
14-concurrency/concurrency/operations.go
Normal file
19
14-concurrency/concurrency/operations.go
Normal file
@@ -0,0 +1,19 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
func CalcStoreTotal(data ProductData) {
|
||||
var storeTotal float64
|
||||
for category, group := range data {
|
||||
storeTotal += group.TotalPrice(category)
|
||||
}
|
||||
fmt.Println("Total: ", ToCurrency(storeTotal))
|
||||
}
|
||||
|
||||
func (group ProductGroup) TotalPrice(category string) (total float64) {
|
||||
for _, p := range group {
|
||||
total += p.Price
|
||||
}
|
||||
fmt.Println(category, "subtotal: ", ToCurrency(total))
|
||||
return
|
||||
}
|
||||
39
14-concurrency/concurrency/product.go
Normal file
39
14-concurrency/concurrency/product.go
Normal file
@@ -0,0 +1,39 @@
|
||||
package main
|
||||
|
||||
import "strconv"
|
||||
|
||||
type Product struct {
|
||||
Name, category string
|
||||
Price float64
|
||||
}
|
||||
|
||||
type ProductGroup []*Product
|
||||
|
||||
var ProductList = []*Product{
|
||||
{"Kayak", "Watersports", 279},
|
||||
{"LifeJacket", "Watersports", 49.95},
|
||||
{"Soccer Ball", "Soccer", 19.50},
|
||||
{"Corner Flags", "Soccer", 34.95},
|
||||
{"Stadium", "Soccer", 79500},
|
||||
{"Thinking Cap", "Chess", 16},
|
||||
{"Unsteady Chair", "Chess", 29.95},
|
||||
{"Bling-Bling King", "Chess", 1200},
|
||||
}
|
||||
|
||||
type ProductData = map[string]ProductGroup
|
||||
|
||||
var Products = make(ProductData)
|
||||
|
||||
func ToCurrency(price float64) string {
|
||||
return "$" + strconv.FormatFloat(price, 'f', 2, 64)
|
||||
}
|
||||
|
||||
func init() {
|
||||
for _, product := range ProductList {
|
||||
if _, ok := Products[product.category]; ok {
|
||||
Products[product.category] = append(Products[product.category], product)
|
||||
} else {
|
||||
Products[product.category] = ProductGroup{}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user