有没有办法将字符串或错误作为通用参数?
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 请求,我希望它是一个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 中是一种没有任何方法的原始数据类型,我想知道是否有可能的方法来做到这一点。
更新:
正如@nipuna 在评论中指出的那样,两者error都不是Stringer。
侃侃无极
相关分类