まとめ:ポインタの理解
CoddyのGOジャーニー「基礎」セクションの一部。レッスン 66/109。
チャレンジ
中級このチャレンジでは、小さな店舗向けのシンプルな在庫管理システムを構築します。ポインターを使用して在庫数量を更新し、値を計算し、変更を追跡します。
以下の3つの関数を完成させてください。
-
updateQuantity(quantity *int, change int) (int, bool)
change(販売の場合は負の値、補充の場合は正の値)を加算して、quantityが指す値を変更します。
結果が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 はアイテムの数量を更新し、新しい数量を返します
// およびアイテムが在庫切れかどうか(quantity = 0)
func updateQuantity(quantity *int, change int) (int, bool) {
// TODO: 数量のポインタを更新し、新しい値と在庫切れステータスを返す
return 0, false
}
// calculateValue は数量と価格に基づいてアイテムの合計価値を計算します
// It also updates the mostValuableItem if this item is more valuable
func calculateValue(itemName string, quantity int, price float64, mostValuableItem *string, highestValue *float64) float64 {
// TODO: Calculate the total value, update mostValuableItem if needed, and return the total value
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 // $0.50 ずつ
orangePrice := 0.7 // $0.70 ずつ
bananaPrice := 0.3 // $0.30 ずつ
// Track the most valuable item
var mostValuableItem string
var highestValue float64
// Display initial inventory
fmt.Println("Initial Inventory:")
displayInventory(&apples, &oranges, &bananas, applePrice, orangePrice, bananaPrice)
// Calculate initial values and find most valuable item
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本売ろうとする(在庫より多い)
// Check if any items are out of stock
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!")
}
// Display updated inventory
fmt.Println("\nUpdated Inventory:")
displayInventory(&apples, &oranges, &bananas, applePrice, orangePrice, bananaPrice)
// Reset most valuable tracking for recalculation
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本追加する
// Display final inventory
fmt.Println("\nFinal Inventory:")
displayInventory(&apples, &oranges, &bananas, applePrice, orangePrice, bananaPrice)
// Reset most valuable tracking for final calculation
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)
}基礎のすべてのレッスン
自分で練習してみよう: Goオンラインコンパイラ