요약 - 동적 리스트
Coddy GO 여정의 기초 섹션에 포함된 레슨 — 109개 중 83번째.
챌린지
중급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])
}
}기초의 모든 레슨
2변수와 기본 자료형
변수란 무엇인가`:=`를 이용한 타입 추론정수 (int)부동 소수점 수불리언 (Booleans)문자열 (Strings)제로 값 (Zero Values)상수명명 규칙요약 - 변수와 타입