まとめ:ポインタの理解
CoddyのGOジャーニー「基礎」セクションの一部 — レッスン 66/109。
チャレンジ
中級このチャレンジでは、小さな店舗向けのシンプルな在庫管理システムを構築します。ポインタを使用して在庫数の更新、価値の計算、および変更の追跡を行います。
以下の3つの関数を完成させてください:
-
updateQuantity(quantity *int, change int) (int, bool)
quantityの値をchange分だけ加算して変更します(売上の場合は負の値、補充の場合は正の値)。
結果が0未満になる場合は、代わりに*quantityを0に設定してください。
新しい数量と、アイテムが在庫切れ(*quantity == 0)になった場合にtrueとなるブール値を返します。 -
calculateValue(itemName string, quantity int, price float64, mostValuableItem *string, highestValue *float64) float64
totalValueをfloat64(quantity) * priceとして計算します。
もしtotalValueが*highestValueより大きい場合は、ポインタを使用して*highestValueを更新し、*mostValuableItemにitemNameを設定します。
totalValueを返します。 -
displayInventory(apples, oranges, bananas *int, applePrice, orangePrice, bananaPrice float64)
fmt.Printfを使用して、各アイテムの名前、数量(ポインタからデリファレンスしたもの)、および計算された価値を表示します。
フォーマット:Apples: 10 (Value: $5.00)— 価格には%.2fを使用してください。
初期在庫の期待される出力は以下の通りです:
Initial Inventory: Apples: 10 (Value: $5.00) Oranges: 15 (Value: $10.50) Bananas: 8 (Value: $2.40) Total inventory value: $17.90 Most valuable item: Oranges
ヒント: ポインタが指す値を読み書きするには *quantity を使用します。例えば、*quantity += change は元の変数を直接変更します。
自分で試してみよう
package main
import "fmt"
// updateQuantity はアイテムの数量を更新し、新しい数量と
// アイテムが在庫切れ(数量 = 0)かどうかを返します
func updateQuantity(quantity *int, change int) (int, bool) {
// TODO: 数量ポインタを更新し、新しい値と在庫切れステータスを返す
return 0, false
}
// calculateValue は数量と価格に基づいてアイテムの合計価値を計算します
// また、このアイテムの方が価値が高い場合は mostValuableItem を更新します
func calculateValue(itemName string, quantity int, price float64, mostValuableItem *string, highestValue *float64) float64 {
// TODO: 合計価値を計算し、必要に応じて mostValuableItem を更新して、合計価値を返す
return 0.0
}
// displayInventory は在庫の詳細を表示します
// 関数がリアルタイムのデータを表示できるようにポインタを受け取ります
func displayInventory(apples, oranges, bananas *int, applePrice, orangePrice, bananaPrice float64) {
fmt.Printf("Apples: %d (Value: $%.2f)\n", *apples, float64(*apples) * applePrice)
fmt.Printf("Oranges: %d (Value: $%.2f)\n", *oranges, float64(*oranges) * orangePrice)
fmt.Printf("Bananas: %d (Value: $%.2f)\n", *bananas, float64(*bananas) * bananaPrice)
}
func main() {
// 在庫の初期化
apples := 10
oranges := 15
bananas := 8
// 価格
applePrice := 0.5 // 1つ $0.50
orangePrice := 0.7 // 1つ $0.70
bananaPrice := 0.3 // 1つ $0.30
// 最も価値のあるアイテムを追跡
var mostValuableItem string
var highestValue float64
// 初期在庫を表示
fmt.Println("Initial Inventory:")
displayInventory(&apples, &oranges, &bananas, applePrice, orangePrice, bananaPrice)
// 初期価値を計算し、最も価値のあるアイテムを見つける
appleValue := calculateValue("Apples", apples, applePrice, &mostValuableItem, &highestValue)
orangeValue := calculateValue("Oranges", oranges, orangePrice, &mostValuableItem, &highestValue)
bananaValue := calculateValue("Bananas", bananas, bananaPrice, &mostValuableItem, &highestValue)
fmt.Printf("Total inventory value: $%.2f\n", appleValue+orangeValue+bananaValue)
fmt.Printf("Most valuable item: %s\n\n", mostValuableItem)
// 売上のシミュレーション
fmt.Println("Processing sales...")
_, applesOutOfStock := updateQuantity(&apples, -4) // りんごを4つ販売
_, orangesOutOfStock := updateQuantity(&oranges, -8) // オレンジを8つ販売
_, bananasOutOfStock := updateQuantity(&bananas, -10) // バナナを10房販売しようとする(在庫以上)
// 在庫切れのアイテムがあるか確認
if applesOutOfStock {
fmt.Println("Apples are out of stock!")
}
if orangesOutOfStock {
fmt.Println("Oranges are out of stock!")
}
if bananasOutOfStock {
fmt.Println("Bananas are out of stock!")
}
// 更新された在庫を表示
fmt.Println("\nUpdated Inventory:")
displayInventory(&apples, &oranges, &bananas, applePrice, orangePrice, bananaPrice)
// 再計算のために最も価値のあるアイテムの追跡をリセット
mostValuableItem = ""
highestValue = 0
// 価値を再計算
appleValue = calculateValue("Apples", apples, applePrice, &mostValuableItem, &highestValue)
orangeValue = calculateValue("Oranges", oranges, orangePrice, &mostValuableItem, &highestValue)
bananaValue = calculateValue("Bananas", bananas, bananaPrice, &mostValuableItem, &highestValue)
fmt.Printf("Total inventory value: $%.2f\n", appleValue+orangeValue+bananaValue)
fmt.Printf("Most valuable item: %s\n\n", mostValuableItem)
// アイテムを補充
fmt.Println("Restocking...")
updateQuantity(&apples, 5) // りんごを5つ追加
updateQuantity(&oranges, 10) // オレンジを10個追加
updateQuantity(&bananas, 12) // バナナを12房追加
// 最終在庫を表示
fmt.Println("\nFinal Inventory:")
displayInventory(&apples, &oranges, &bananas, applePrice, orangePrice, bananaPrice)
// 最終計算のために最も価値のあるアイテムの追跡をリセット
mostValuableItem = ""
highestValue = 0
// 最終的な価値の計算
appleValue = calculateValue("Apples", apples, applePrice, &mostValuableItem, &highestValue)
orangeValue = calculateValue("Oranges", oranges, orangePrice, &mostValuableItem, &highestValue)
bananaValue = calculateValue("Bananas", bananas, bananaPrice, &mostValuableItem, &highestValue)
fmt.Printf("Total inventory value: $%.2f\n", appleValue+orangeValue+bananaValue)
fmt.Printf("Most valuable item: %s\n", mostValuableItem)
}