1 回答
TA贡献1805条经验 获得超9个赞
您可以更改mainErrorModel为struct with no pointer带有类型断言,然后将该结构更改为struct with pointer,最后您可以再次更改为Failure带有类型断言的类型接口。
这是例子。
// You can edit this code!
// Click here and start typing.
package main
import (
"fmt"
)
type GenericOpenAPIError interface {
Model() any
}
type Failure interface {
GetErrors() string
}
type GenericOpenAPI struct {
model any
}
func (g *GenericOpenAPI) Model() any {
return g.model
}
func (g *GenericOpenAPI) Error() string {
return "goae error"
}
type A struct {
b string
}
func (a *A) GetErrors() string {
return a.b
}
type B struct {
c string
}
func (b *B) GetErrors() string {
return b.c
}
type GetErrores interface {
A | B
}
func getErrorMessage[T GetErrores](err error) string {
if mainError, ok1 := err.(GenericOpenAPIError); ok1 {
var mainErrorModel = mainError.Model()
if t, ok := mainErrorModel.(T); ok {
if f, ok := any(&t).(Failure); ok { // must change &t to any then type assert to Failure to tell app that there is a method GetErrors()
return f.GetErrors()
}
}
}
return err.Error()
}
func main() {
var err any
err = &GenericOpenAPI{A{b: "this is error a"}}
e, ok := err.(error)
if !ok {
panic("not ok!")
}
fmt.Println(getErrorMessage[A](e))
// change model to B
err = &GenericOpenAPI{B{c: "this is error b"}}
e, ok = err.(error)
if !ok {
panic("not ok!")
}
fmt.Println(getErrorMessage[B](e))
}
- 1 回答
- 0 关注
- 100 浏览
添加回答
举报