[英]How can I write a function in Golang which takes multiple types as a parameter?
[英]How to write a generic function that takes a string or an error as a parameter?
有沒有辦法將字符串或錯誤作為通用參數?
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})
}
上面的代碼包含一個 helper function 嘗試用一個 json 來響應一個 http 請求,其中包含一個通用字段,我希望它是一個string
或一個error
。
但是當我嘗試輸入一個字符串時:
string does not implement fmt.Stringer (missing method String)
我覺得這很有趣。
我試圖將T fmt.Stringer
更改為T string | fmt.Stringer
T string | fmt.Stringer
.縱梁:
cannot use fmt.Stringer in union (fmt.Stringer contains methods)
我理解的原因是 golang 中的string
是一種沒有任何方法的原始數據類型,我想知道是否有可能的方法來做到這一點。
更新:
正如@nipuna 在評論中指出的那樣, error
也不是Stringer
。
有沒有辦法將字符串或錯誤作為通用參數?
不,如前所述,您正在尋找的約束是~string | error
~string | error
,這不起作用,因為不能在聯合中使用帶有方法的接口。
error
確實是一個帶有Error() string
方法的接口。
處理這個問題的明智方法是刪除 generics 並將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()})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.