go 范型函数断言

122 阅读1分钟

定义两个结构体,和各自的方法

type a struct {    
    A string
}
func (aa a) Is() {
    fmt.Print("AAAAA")
}
type b struct {
    B int
}
func (bb b) Is() {
    fmt.Print("BBBBB")
}

定义一个范型函数,返回指定的结果体

func GetAorB[T a | b]() T {
    var t T
    var tmp any = t
    switch tmp.(type) {
    case a:
        tmp = a{
            A: "aaaaa",
        }
    case b:
        tmp = b{
            B: 123,
        }
    }
    return tmp.(T)
}

调用范型函数,返回对应的结构体,各自结构体可调用自己方法

func TestGetAorB(t *testing.T) {
    a := GetAorB[a]()
    t.Logf("a: %v", a.A)
    a.Is()
    b := GetAorB[b]()
    t.Logf("b: %v", b.B)
    b.Is()
}