1 回答

TA貢獻(xiàn)1805條經(jīng)驗(yàn) 獲得超9個(gè)贊
您可以更改mainErrorModel為struct with no pointer帶有類型斷言,然后將該結(jié)構(gòu)更改為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 關(guān)注
- 124 瀏覽
添加回答
舉報(bào)