Kodewick
学びはじめる →
基礎←→0 / 70

何杯にしますか?

#057基礎strconv.Atoi約 4 分

紅茶のお店の注文欄に、お客さんが何杯ほしいかを入力します。Cups(text) はすでに strconv.Atoi で文字列を数値に変え、数値でなければエラーを返します。もう 1 つのチェックを加えましょう。1 杯より少ないのもだめなので、0 とエラー "at least 1 cup" を返します。

例
Cups("3")→(3, None)
Cups("two")→(0, 'not a number')
Cups("0")→(0, 'at least 1 cup')
関数func Cups(text string) (int, error)
main.go
package main

import (
	"errors"
	"strconv"
)

func Cups(text string) (int, error) {
	n, err := strconv.Atoi(text)
	if err != nil {
		return 0, errors.New("not a number")
	}
	// ここにコードを書く:n が 1 より小さければ、0 とエラー "at least 1 cup" を返す
	return n, nil
}
Ctrl + Enter でも実行できます
結果

実行すると例で試せます。よさそうなら提出しましょう。