有沒有辦法將字符串或錯誤作為通用參數(shù)?package controllerimport ( "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})}上面的代碼包含一個輔助函數(shù),它試圖用一個包含一個通用字段的 json 來響應 http 請求,我希望它是一個string或一個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 中是一種沒有任何方法的原始數(shù)據(jù)類型,我想知道是否有可能的方法來做到這一點。更新:正如@nipuna 在評論中指出的那樣,兩者error都不是Stringer。
1 回答

侃侃無極
TA貢獻2051條經(jīng)驗 獲得超10個贊
有沒有辦法將字符串或錯誤作為通用參數(shù)?
不,如前所述,您正在尋找的約束是~string | error
,它不起作用,因為帶有方法的接口不能在聯(lián)合中使用。
并且error
確實是一個帶有方法的接口Error() string
。
處理這個問題的明智方法是放棄泛型并定義Reason
為string
:
type ServerError struct { Reason string `json:"reason"`}
您可以在此處找到更多詳細信息:Golang Error Types are empty when encoded to 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()})
- 1 回答
- 0 關(guān)注
- 85 瀏覽
添加回答
舉報
0/150
提交
取消