Error handling 返回结构时转到错误处理
据我所知(从standerd库和从standerd库的阅读中),在一个库中处理返回数据和错误的idomatic方法 问题是,当我必须返回一个错误时,我应该返回什么作为我的数据?空结构?0 这里有一个例子Error handling 返回结构时转到错误处理,error-handling,go,Error Handling,Go,据我所知(从standerd库和从standerd库的阅读中),在一个库中处理返回数据和错误的idomatic方法 问题是,当我必须返回一个错误时,我应该返回什么作为我的数据?空结构?0 这里有一个例子 // Load the config func LoadConfig(location string) (Config, error) { // Read the file configFile, err := ioutil.ReadFile(location) if e
// 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
}
这是惯用语吗?取决于上下文。您可以返回相应类型的空值,如果返回的类型是指针,则返回
nil
。但如果对函数有意义的话,还可以返回部分结果和错误。例如,在bufio
packageReader.ReadString
中返回字符串和错误。委员会:
如果ReadString在查找分隔符之前遇到错误,它将返回在错误之前读取的数据以及错误本身(通常是io.EOF)
除了你的问题(已经有了一个很好的答案),还有一件事需要注意-在你的例子中,你当然还应该返回来自
json.Unmarshal
的错误。@Not_a_Golfer谢谢,我错过了那一个。谢谢,这就是我所想的。