亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

用另一個 void 函數的結果返回 void 函數?

用另一個 void 函數的結果返回 void 函數?

Go
Helenr 2021-12-07 10:45:56
我正在嘗試提出一種非常緊湊的方法來處理 REST API 的 HTTP 請求中可能出現的問題。我需要測試許多條件,以及對這些條件中的任何一個失敗的許多潛在錯誤響應。我已經將我的處理流程簡化為類似于以下內容的內容:// Error is actually a method on some struct, so it's only relevant for demonstration purposes.func Error(w http.ResponseWriter, status int, message string) {  // Lots of stuff omitted  w.WriteHeader(status)  w.WriteJson(r)}func HandleSomething(w http.ResponseWriter, r *http.Request) {  if someCondition != true {    Error(w, 500, "Some error occurred!")    return  }  if someOtherCondition != true {    Error(w, 500, "Some other error occurred!")    return  }  if yetAnotherCondition != true {    Error(w, 500, "Yet another error occurred!")    return  }  if andFinallyOneLastCondition != true {    Error(w, 500, "One final error occurred!")    return  }  // All good! Send back some real data.  w.WriteJson(someObject)}由于我經常需要測試 5-10 個條件,以及在其他操作期間可能出現的其他錯誤,因此能夠將其壓縮為以下內容會很好:func HandleSomething(w http.ResponseWriter, r *http.Request) {  if someCondition != true {    return Error(w, 500, "Some error occurred!")  }  if someOtherCondition != true {    return Error(w, 500, "Some other error occurred!")  }  if yetAnotherCondition != true {    return Error(w, 500, "Yet another error occurred!")  }  if andFinallyOneLastCondition != true {    return Error(w, 500, "One final error occurred!")  }  // All good! Send back some real data.  w.WriteJson(someObject)}但是,Go 編譯器不喜歡這樣。它既抱怨我試圖將結果Error()用作值,又抱怨我試圖返回太多參數。確切的錯誤消息是:foo.go:41: bar.Response.Error(400, "InvalidRequest", "Error decoding request") used as valuefoo.go:41: too many arguments to return但兩者Error()并HandleSomething()具有相同的返回簽名(例如,它們都返回什么),所以不宜這項工作?每個if語句都包含 a很重要return,因為函數應該立即退出。如果Error()可以以某種方式停止調用函數的執行,那也對我有用。testing.FailNow()有點像,但我相信這依賴于 Goroutines。順便說一句:我意識到這些并不是真正的“空”函數,但想不出更合適的名稱。在 Go 中不返回任何內容的函數是否有合適的名稱?
查看完整描述

2 回答

?
千萬里不及你

TA貢獻1784條經驗 獲得超9個贊

我不確定,但我會用 if-else 方式來做


func HandleSomething(w http.ResponseWriter, r *http.Request) {

  if someCondition != true {

    Error(w, 500, "Some error occurred!")

  } else if someOtherCondition != true {

    Error(w, 500, "Some other error occurred!")

  } else if yetAnotherCondition != true {

    Error(w, 500, "Yet another error occurred!")

  } else if andFinallyOneLastCondition != true {

    Error(w, 500, "One final error occurred!")

  } else {

    // All good! Send back some real data.

    w.WriteJson(someObject)

  }

}


查看完整回答
反對 回復 2021-12-07
?
忽然笑

TA貢獻1806條經驗 獲得超5個贊

C++ 允許這樣做。它對模板非常方便。

但正如你所見,Go 沒有。我不確定確切的步驟,但這似乎是您可以要求添加到 Go 中的東西,也許它可以用于 1.7。

至于現在的解決方案,也許您可以返回一個未使用的error. 只需將其nil從您的Error函數中返回即可。


查看完整回答
反對 回復 2021-12-07
  • 2 回答
  • 0 關注
  • 247 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號