有沒有辦法將字串或錯誤作為通用引數?
package controller
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
)
type ServerError[T fmt.Stringer] struct {
Reason T `json:"reason"`
}
func ResponseWithBadRequest[T fmt.Stringer](c *gin.Context, reason T) {
c.AbortWithStatusJSON(http.StatusBadRequest, ServerError[T]{Reason: reason})
}
上面的代碼包含一個幫助函式,它嘗試使用包含一個通用欄位的 json 回應 http 請求,我希望它是 astring或error.
但是當我嘗試輸入一個字串時:
string does not implement fmt.Stringer (missing method String)
我覺得很有趣。
我試圖更改T fmt.Stringer為T string | fmt.Stringer:
cannot use fmt.Stringer in union (fmt.Stringer contains methods)
我理解原因是string在 golang 中是一種沒有任何方法的原始資料型別,我想知道是否有可能的方法來做到這一點。
更新:
正如@nipuna 在評論中指出的那樣,error也不Stringer是。
uj5u.com熱心網友回復:
有沒有辦法將字串或錯誤作為通用引數?
不。如上所述,您正在尋找的約束是~string | error,它不起作用,因為不能在聯合中使用帶有方法的介面。
而且error確實是Error() string方法的介面。
處理此問題的明智方法是洗掉泛型并定義Reason為string:
type ServerError struct {
Reason string `json:"reason"`
}
您可以在此處找到更多詳細資訊:Golang 錯誤型別在編碼為 JSON 時為空。tl;dr 是error 不能直接編碼為 JSON 的;無論如何,您最終都必須提取其字串訊息。
所以最后你要用字串做這樣的事情:
reason := "something was wrong"
c.AbortWithStatusJSON(http.StatusBadRequest, ServerError{reason})
和這樣的錯誤:
reason := errors.New("something was wrong")
c.AbortWithStatusJSON(http.StatusBadRequest, ServerError{reason.Error()})
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/511214.html
標籤:去仿制药
上一篇:如何從父抽象類回傳繼承類的實體
