【发布时间】:2020-04-08 02:27:51
【问题描述】:
学习 Go 并参考https://tour.golang.org/methods/20
package main
import (
"fmt"
"math"
)
type ErrNegativeSqrt float64 //This is the custom Struct
func (e ErrNegativeSqrt) Error() string {
return fmt.Sprintf("cannot Sqrt negative number: %g", float64(e))
}
func Sqrt(x float64) (float64, error) { // Is error a type ?
if(x < 0){
return x, ErrNegativeSqrt(x) //Q1) If error is a type, How come ErrNegativeSqrt(x) is of type error?
}
z := float64(1.5)
val := float64(0)
for {
z = z - (z*z-x)/(2*z)
if math.Abs(val-z) < 1e-10 {
break
}
val = z
}
return val, nil
}
func main() {
fmt.Println(Sqrt(2))
fmt.Println(Sqrt(-2))
}
Q2) 为什么在 Error 方法中调用 fmt.Sprint(e) 会使程序陷入死循环?
【问题讨论】:
-
Q2) 发生无限递归是因为
fmt在后台查看提供的值,如果该值实现特定接口,它将调用其主要方法,在本例中为Error方法error接口,但实现Stringer接口的类型也容易受到此影响。因此,在这些类型的方法中,如果他们想将接收器传递给fmt,则将接收器转换为不实现这些接口的类型,就像您在float64(e)的示例中看到的那样,这一点很重要。跨度> -
您的标题询问了自定义结构,但您的示例甚至没有使用严格的结构。这是一个 float64。
标签: go struct types error-handling