요약 - 포인터의 이해
Coddy GO 여정의 기초 섹션에 포함된 레슨 — 109개 중 66번째.
챌린지
중급이 챌린지에서는 작은 상점을 위한 간단한 재고 관리 시스템을 구축하게 됩니다. 포인터를 사용하여 재고 수량을 업데이트하고, 가치를 계산하며, 변경 사항을 추적합니다.
아래의 세 가지 함수를 완성하세요:
-
updateQuantity(quantity *int, change int) (int, bool)
quantity가 가리키는 값에change를 더하여 수정합니다 (판매 시 음수, 재입고 시 양수).
결과가0미만이 될 경우,*quantity를0으로 설정합니다.
새로운 수량과 해당 품목이 품절 상태(*quantity == 0)인지 여부를 나타내는 불리언 값을 반환합니다. -
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 // 개당 $0.50
orangePrice := 0.7 // 개당 $0.70
bananaPrice := 0.3 // 개당 $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)
}기초의 모든 레슨
2변수와 기본 자료형
변수란 무엇인가`:=`를 이용한 타입 추론정수 (int)부동 소수점 수불리언 (Booleans)문자열 (Strings)제로 값 (Zero Values)상수명명 규칙요약 - 변수와 타입