Return errors in Go by adding 'error' to the function signature and returning an error value created with errors.New or fmt.Errorf.
Return an error by adding error to your function's return type and using return with an error value created by errors.New or fmt.Errorf.
func readFile(name string) (string, error) {
if name == "" {
return "", errors.New("filename cannot be empty")
}
return "content", nil
}
The caller must check the error: if err != nil { /* handle error */ }.
In Go, functions signal problems by returning a special 'error' value alongside their normal result. Think of it like a delivery driver handing you a package and a receipt; if the receipt says 'damaged,' you know not to open the package. This forces you to explicitly check for problems before using the result.