As far as I can tell(from here, and from reading the standerd library), the idomatic way of handling errors in a library returning both your data and an error.
The question is, when I do run have to return an error, what do I return as my data? An empty struct? 0?
Here is an example
// Load the config
func LoadConfig(location string) (Config, error) {
// Read the file
configFile, err := ioutil.ReadFile(location)
if err != nil {
return Config{}, err
}
// Convert it to Config struct
var config Config
json.Unmarshal(configFile, &config)
return config, nil
}
Is this idiomatic?
Depends on the context. You can return the empty value for the corresponding type or nil
if the returned type is a pointer. But you could also return partial result together with the error if that makes sense for the function. For example in bufio
package Reader.ReadString
returns string and error. The docs state:
If ReadString encounters an error before finding a delimiter, it returns the data read before the error and the error itself (often io.EOF).