为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
开满天机 2023-02-21 16:46:02
有没有办法将字符串或错误作为通用参数?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})}上面的代码包含一个辅助函数,它试图用一个包含一个通用字段的 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。
查看完整描述

1 回答

?
侃侃无极

TA贡献2051条经验 获得超10个赞

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

不,如前所述,您正在寻找的约束是~string | error,它不起作用,因为带有方法的接口不能在联合中使用。

并且error确实是一个带有方法的接口Error() string

处理这个问题的明智方法是放弃泛型并定义Reasonstring

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()})


查看完整回答
反对 回复 2023-02-21
  • 1 回答
  • 0 关注
  • 51 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信