有没有办法将字符串或错误作为泛型参数?
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})
}
上面的代码包含一个帮助器函数,它try 用一个包含一个通用字段的json来响应http请求,我希望它是string
或error
.
但当我try 输入字符串时:
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)
我理解的原因是,Golang中的string
是一个没有任何方法的原始数据类型,我想知道是否有可能做到这一点的方法.
Update:个
正如@nipuna在 comments 中指出的那样,error
也不是Stringer
.