[Go] golang的error接口
2023-02-18 15:47:28 时间
error接口
1.error就是一个接口interface
2.属于errors包,该包有一个导出方法New,返回了errorString类型
3.errorString类型实现了error接口
4.之所以这样是因为可以实现每个错误都是不同的实例
package main import ( "errors" "fmt" "syscall" ) /* errors包中的代码 package errors //定义了接口 type error interface { Error() string } //大写字母开头的方法,可以导出 //返回了errorStrig类型 func New(text string) error { return &errorString{text} } //定义类型 type errorString struct { text string } //类型实现接口的方法 func (e *errorString) Error() string { return e.text } */ func main() { //返回false,这俩是不相同的实例 fmt.Println(errors.New("tsh error") == errors.New("tsh error")) //fmt.Errorf进行了包装 fmt.Println(fmt.Errorf("我是 %s 错误", "tsh")) //类似实现了error接口 var err error = syscall.Errno(2) fmt.Println(err.Error()) fmt.Println(err) }
相关文章
- Go语言中常见100问题-#1 Unintended variable shadowing
- Go语言中常见100问题-#2 Unnecessary nested code
- Go语言中常见100问题-#3 Misusing init functions
- Go语言中常见100问题-#4 Overusing getters and setters
- Go语言中常见100问题-#5 Interface pollution
- Go语言中常见100问题-#6 Interface on the producer side
- Go语言中常见100问题-#7 Returning interfaces
- Go语言中常见100问题-#8 any says nothing
- Go语言中常见100问题-#9 Being confused about when to use generics
- Go语言中常见100问题-#10 Not being aware of the possible problems ...
- Go语言中常见100问题-#11 Not using the functional options pattern
- Go语言中常见100问题-#12 Project misorganization
- Go语言中常见100问题-#13 Creating utility packages
- Go语言中常见100问题-#14 Ignoring package name collisions
- Go语言中常见100问题-#15 Missing code documentation
- Go语言中常见100问题-#16 Not using linters
- Go语言中常见100问题-#17 Creating confusion with octal literals
- Go语言中常见100问题-#18 Neglecting integer overflows
- Go语言中常见100问题-#19 Not understanding floating points
- Go语言中常见100问题-#20 Not understanding slice length and capacity