賬單上的每一行是一個 Line:名字、單價 Price、數量 Qty。先給 Line 寫方法 Cost(),返回這一行的錢(單價乘數量);再寫 Receipt(lines),用它把整張賬單加起來。空賬單就是 0。
Receipt([]Line{{"pencil", 2, 5}, {"notebook", 8, 1}})→18Receipt([]Line{})→0func Receipt(lines []Line) intpackage main
type Line struct {
Name string
Price int
Qty int
}
func (l Line) Cost() int {
// 在這裡寫:返回單價乘數量
return 0
}
func Receipt(lines []Line) int {
total := 0
for _, l := range lines {
// 在這裡寫:把這一行的 Cost() 加進 total
}
return total
}
寫好了先點「執行」試試示例,沒問題再點「提交」。