Implement the error interface in Go by defining a type with an Error() string method.
Implement the error interface by defining a type with a method named Error that returns a string. Any type with this method automatically satisfies the interface.
type MyError struct {
msg string
}
func (e MyError) Error() string {
return e.msg
}
func main() {
var err error = MyError{"something went wrong"}
fmt.Println(err) // prints: something went wrong
}
In Go, an interface is a contract that a type must fulfill to be used in specific ways. To make your custom error work with standard error handling, you just need to add a method called Error that returns a text description. Think of it like a label on a box; as long as the box has a label that says what's inside, the system knows how to handle it.