[英]What is the idiomatic way to handle nil and error in Golang?
我有2個go函數:
func sampleFunction () {
u, err := findDog(1)
if err != nil {
// We couldn't find the dog, print a message.
fmt.Println(err)
// Custom error types.
if _, ok := err.(*dneError); ok {
fmt.Println("Custom dog dne error for the end-user here.")
}
} else {
// Do something with u.
u.doSomething() // Is this idiomatic in Go?
// Should we explicility check for u != nil?
// Or does the if check above need to return?
// (even if I would like the function to be longer)
}
}
// findDog returns a dog with a given ID. If not found, returns an error.
func findDog(id int) (*models.Dog, error) {
found, err := models.FindDog(id)
// Is this return scheme/flow too brittle?
if err != nil {
return nil, &dneError{fmt.Sprintf("Dog %d does not exist in the" +
"database: %s", id, err.Error())}
}
return found, nil
}
我只想確保我正確地處理了錯誤和錯誤,所以我的兩個主要問題是:
在findDog中,兩種情況下我是否都適當返回nil?
在sampleFunction中,不顯式檢查u!= nil是否很常見,或者我只是完全錯誤地執行了此操作?
我的目標是在程序員需要時正確地顯示錯誤/問題,並在需要時向用戶顯示錯誤/問題,同時還要遵循慣用的標准。 感謝您的時間。
是的,這是慣用的Go。 因為錯誤是預先處理的,所以錯誤意味着出現故障,結果為nil
,或者例如部分寫入的緩沖區沒有任何用處。
PS我也有一個建議,可以使事情更加慣用。 習慣用法類似於“縮進錯誤塊,而不是代碼”。 具體來說,您在sampleFunction
有一個if / else,但是在大多數錯誤檢查情況下(不是全部),您將其處理並返回,然后跳過else並繼續進行流程。 為什么不必縮進? 這具有使甚至很長的函數易於閱讀的效果,因為該函數的預期流程可以從上至下讀取,而不必在if / else塊之間來回跳動。 至少在很多場合。
我對某人的存儲庫提出了一個拉取請求,因為我有一個if / else,其中if with return就足夠了。
編輯所以我的回答有點困擾我,現在我記得為什么。 這是通常慣用的非nil
error
返回指示其他的返回值(一個或多個)是無用的,但確實有例外。 確保檢查各個文檔。
作為一個具體的示例,請參見bytes.Buffer.ReadBytes
如果ReadBytes在找到定界符之前遇到錯誤,它將返回錯誤之前讀取的數據和錯誤本身(通常為io.EOF)。
我個人認為您處理得很好,只是一個建議,因為我不知道使用什么模型。我會仔細檢查found
models.FindDog(id)
,如果這是nil
返回錯誤,總結if err != nil || found == nil {
if err != nil || found == nil {
注意:執行此return err.Error()
可能會失敗
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.