計分板上的分數是大家手打的字。寫 TotalScores(texts):空字串 "" 是沒來的人,跳過;有一個不是數,就馬上返回 0 和 strconv.Atoi 給的那個錯誤;都沒問題就返回總分和 nil。
TotalScores([]string{"8", "", "7"})→(15, None)TotalScores([]string{"9", "ten"})→(0, 'strconv.Atoi: parsing "ten": invalid syntax')func TotalScores(texts []string) (int, error)package main
import "strconv"
func TotalScores(texts []string) (int, error) {
total := 0
for _, t := range texts {
// 在這裡寫:t 是空字串就跳過
n, err := strconv.Atoi(t)
if err != nil {
// 在這裡寫:返回 0 和 err
}
total += n
}
return total, nil
}
寫好了先點「執行」試試示例,沒問題再點「提交」。