繁体   English   中英

如何编写一个将字符串或错误作为参数的通用 function?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM