![](/img/trans.png)
[英]How can I write a function in Golang which takes multiple types as a parameter?
[英]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.