Error
Go error就是一个普通的接口,普通的值。
http://golang.org/pkg/builtin/#error
type error interface {
Error() string
}
我们常用一个errors.New()来返回一个error对象。
http://golang.org/src/pkg/errors/errors.go
type errorString struct {
s string
}
http://golang.org/src/pkg/errors/errors.go
func (e *errorString) Error() string {
return e.s
}
基础库中大量自定义的error:
http://golang.org/src/pkg/bufio/bufio.go
var (
ErrInvalidUnreadByte = errors.New("Bufio: invalid use of UnreadByte")
...
)
errors.New()返回的是内部errorString对象的指针
http://golang.org/src/pkg/errors/errors.go
// 每次返回一个新的对象,取其地址,防止两次error new同样text时两次对象相等
func New(text string) error {
return &errorString{
text}
}
例子:
package main
import (
"errors"
"fmt"
)
// create a named type for our new type.
type errorString string
// implement the error interface.
func (e errorString)