計算機科学のブログ

call me - Functions - Using multiple return values, error

Head First GoJay McGavren(著)、O’Reilly Media)の Chapter 3(call me - Functions)、p.101(Pool Puzzle)の解答を求めてみる。

コード

sample.go

package main

import (
	"errors"
	"fmt"
)

func divide(dividend float64, divisor float64) (float64, error) {
	if divisor == 0.0 {
		return 0, errors.New("can't divide by 0")
	}
	return dividend / divisor, nil
}
func main() {
	quotient, err := divide(5.6, 0.0)
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Printf("%0.2f\n", quotient)
	}
}

入出力結果(Terminal, Zsh)

% go run ./sample.go 
can't divide by 0
%