まとめ:動的リスト
CoddyのGOジャーニー「基礎」セクションの一部 — レッスン 83/109。
チャレンジ
中級Goのスライスを扱う練習として、シンプルなショッピングリストマネージャーを作成しましょう!
あなたのタスクは、ショッピングリストを操作するいくつかの関数を実装することです:
addItems: ショッピングリストに新しいアイテムを追加しますremoveItem: インデックスを指定してリストからアイテムを削除しますfindExpensiveItems: しきい値を超える価格のアイテムを見つけますcalculateTotalCost: すべてのアイテムの合計金額を計算します
ショッピングリストの各アイテムは、文字列(名前)と float64(価格)で表されます。main関数では、これらすべての操作が連携して動作する様子を示しています。
自分で試してみよう
package main
import "fmt"
// addItems は、新しいアイテムとその価格をショッピングリストに追加します
func addItems(names []string, prices []float64, newNames []string, newPrices []float64) ([]string, []float64) {
// ここにコードを記述してください
return names, prices
}
// removeItem は、指定されたインデックスのアイテムを削除します
func removeItem(names []string, prices []float64, index int) ([]string, []float64) {
// ここにコードを記述してください
return names, prices
}
// findExpensiveItems は、しきい値を超える価格のアイテムを返します
func findExpensiveItems(names []string, prices []float64, threshold float64) []string {
// ここにコードを記述してください
return nil
}
// calculateTotalCost は、すべての価格の合計を返します
func calculateTotalCost(prices []float64) float64 {
// ここにコードを記述してください
return 0
}
func main() {
// 空のショッピングリストを初期化します
names := []string{}
prices := []float64{}
// 初期アイテムを追加します
initialNames := []string{"Apples", "Milk", "Bread"}
initialPrices := []float64{2.99, 3.49, 2.29}
names, prices = addItems(names, prices, initialNames, initialPrices)
// 初期のショッピングリストを表示します
fmt.Println("Initial Shopping List:")
for i := range names {
fmt.Printf("%d. %s - $%.2f\n", i, names[i], prices[i])
}
// 合計金額を計算して表示します
total := calculateTotalCost(prices)
fmt.Printf("\nTotal Cost: $%.2f\n", total)
// 高額なアイテムを検索して表示します
priceThreshold := 3.00
expensiveItems := findExpensiveItems(names, prices, priceThreshold)
fmt.Printf("\nExpensive Items (above $%.2f):\n", priceThreshold)
for _, item := range expensiveItems {
fmt.Println(item)
}
// 新しいアイテムを追加します
names, prices = addItems(names, prices, []string{"Cheese"}, []float64{4.99})
// アイテムを削除します
names, prices = removeItem(names, prices, 1)
fmt.Println("\nRemoved item at index 1")
// 最終的なショッピングリストを表示します
fmt.Println("\nFinal Shopping List:")
for i := range names {
fmt.Printf("%d. %s - $%.2f\n", i, names[i], prices[i])
}
}