How to Return an Error from a Function in Go

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 */ }.