如何编写一个以字符串或错误作为参数的泛型函数?

有没有办法将字符串或错误作为通用参数?


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。


开满天机
浏览 52回答 1
1回答

侃侃无极

有没有办法将字符串或错误作为通用参数?不,如前所述,您正在寻找的约束是~string | error,它不起作用,因为带有方法的接口不能在联合中使用。并且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()})
打开App,查看更多内容
随时随地看视频慕课网APP