与其他编程语言的差异

1.没有异常机制

2.error类型实现 error接口

  Type error interface{

Error() String

}

4.可以通过errors.New() 快速创建错误实例

 

最佳实践: 及早失败,避免嵌套,直接上代码:

package ch14

import (
   "errors"
   "testing"
)

func Fib(n int  )([]int,error) {
   if n<2||n>100 {
      return nil,errors.New("n should be in[2,100]")
   }
   fiblist:=[] int {1,1}
   for i:=2;i<n;i++{
      fiblist=append(fiblist,fiblist[i-2]+fiblist[i-1])
   }
   return  fiblist,nil
   
}
func TestDemo( t *testing.T)  {

   if v,error:= Fib(50);error!=nil{
      t.Error(error)
   } else {
      t.Log(v)
   }
}

 

GO 错误机制

相关文章: