In Go, returning an error from a function is a common and idiomatic way of handling errors. Here's how you can return an error from a function in Go:
type MyError struct {
Message string
}
error
interface for the error type:func (e *MyError) Error() string {
return e.Message
}
func doSomething() error {
// If an error occurs, return an instance of the error type
if condition {
return &MyError{
Message: "Something went wrong",
}
}
// No error, return nil
return nil
}
err := doSomething()
if err != nil {
// Handle the error
fmt.Println(err)
}
This way, your function doSomething
can indicate that an error occurred by returning a non-nil error value of the appropriate type, and the calling code can react accordingly.