go:errors:error_interface
Table of Contents
error interface
What is it?
`error` is a built-in interface type in Go:
type error interface { Error() string }
Any type that implements `Error() string` can be used as an error.
What is it used for?
- Standardize how functions return failure information.
- Allow custom error types while still matching `error`.
Example
type MyError struct{ Msg string } func (e MyError) Error() string { return e.Msg } func f() error { return MyError{Msg: "something went wrong"} }
Notes
- `nil` error means success.
- Be careful: an interface can be non-nil even if it holds a typed nil (advanced pitfall).
Hard words (English)
- interface /ˈɪntərfeɪs/: giao diện
- implement /ˈɪmplɪment/: triển khai
- pitfall /ˈpɪtfɔːl/: bẫy thường gặp
go/errors/error_interface.txt · Last modified: by phong2018
