[A Tour of Go] Excercise: Errors

newbieski·2023년 4월 10일
0

golang

목록 보기
5/13

https://go.dev/tour/methods/20

package main

import (
	"fmt"
	"math"
)

type ErrNegativeSqrt float64

func (e ErrNegativeSqrt) Error() string {
	return fmt.Sprintf("cannot Sqrt negative number: %f", e)
}


func Sqrt(x float64) (float64, error) {
	if x >= 0 {
		return math.Sqrt(x), nil
	}
	return 0, ErrNegativeSqrt(x)
}

func main() {
	fmt.Println(Sqrt(2))
	fmt.Println(Sqrt(-2))
	//x := ErrNegativeSqrt(-1)
	//fmt.Println(x.Error())
	//fmt.Println("%T", x)
}
profile
newbieski

0개의 댓글