まとめ:動的リスト
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 は指定された index の商品を削除する
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])
}
}基礎のすべてのレッスン
自分で練習してみよう: Goオンラインコンパイラ