《Go源码解读篇》之 Error

Go 语言中必不可少的类型 --- error,Go 中的原生代码少,而且易掌握.

What is error?

官方解释,error 是一个內建接口,定义如下:

// The error build-in interface type is the conventional
// interface for representing an error condition, with
// the nil value representing no error.
type error interface {
    Error() string
}

了解了 error 类型后我们就可以很轻松解读 errors 目录下的源码啦.

Reading errors.go of the errors package

看下源码吧,真的很少.

// New returns an error that formats as the given text.
func New(text string) error {
    return &errorString{text}
}

// errorString is a trivial implementation of error.
type errorString struct {
    s string
}

func (e *errorString) Error() string {
    return e.s
}

这里涉及到了一个知识点,就是对 interface 的理解, 如果理解了这一点, 任意数据类型实现了接口中的所有方法, 那么这个数据类型就实现了该接口. 那就无障碍的搞明白上面的代码了.

我遇到的 interface 使用场景

我感觉 interface 是个全能选手, 使用的范围很多, 如果想了解更全面的了解 interface, 请自行搜索吧, 这里总结下我遇到的 interface 使用场景:

  • interface 接口
  • interface 值&参数

interface 接口

Go 中的 intetface 不同于其他语言 (Java, C#...), 只需要实现其接口内的所有方法, 就是实现该接口, 不用像 Java 似的 implements InterfaceName. 如上 errors 中的栗子:

// 接口: error
// errorString 实现了 Error()方法, 即实现了 error 接口

interface 值&参数

interface 能存什么值呢?答案是:什么值都能存,万能的.就跟 Java 中的 Object 似的.正是如此,广范用于反射.说了三个实际的应用场景:

  • 设计一个链表,每个结点上值的类型是任意的,那么这个值的数据类型就用 interface 来声明:val interface
  • 设计一个方法,其有一个参数是任意类型那么,这个参数类型就用 interface 来声明:param interface{}
  • 设计一个方法,其中参数类型是任意的,参数的个数也是任意的,这是也用interface 来声明:params ...interface{}

以上是学习后的总结,如有错误,还请斧正.

精彩文章,持续更新,请关注微信公众号:

《Go源码解读篇》之 Error_第1张图片
帅哥美女扫一扫

你可能感兴趣的:(《Go源码解读篇》之 Error)