Go语言中的接口、错误处理、泛型与反射
1. 错误数据类型
错误数据类型是一个接口,定义如下:
type error interface {
Error() string
}
要满足错误接口,只需实现 Error() string 类型的方法。当你想为错误条件提供更多上下文时,就应该自己实现错误接口。
在文件读取场景中,当文件没有更多内容可读时,Go会返回 io.EOF 错误。但这严格来说不是错误,而是文件读取的逻辑部分。为了区分空文件和已完全读取的文件,可以借助错误接口。
以下是 errorInt.go 的代码(省略包和导入块):
type emptyFile struct {
Ended bool
Read int
}
// Implement error interface
func (e emptyFile) Error() string {
return fmt.Sprintf("Ended with io.EOF (%t) but read (%d) bytes",
e.Ended, e.Read)
}
// Check values
func isFileEmpty(e error) bool {
// Type assertion
v, ok := e.(emptyFile)
if ok {
if v.Read ==
超级会员免费看
订阅专栏 解锁全文
43

被折叠的 条评论
为什么被折叠?



