dtjbcda841554
2017-09-13 21:04
采纳率: 0%
浏览 17
已采纳

如何从GO结构获取嵌入式类型?

I am trying to get embedded type from Go structs. Below is an example program that demonstrates this. Is there a way to write myfunc() without enumerating every type that can come in as input? https://play.golang.org/p/5wp14O660m

package main

import (
    "fmt"
)

type ObjectMeta struct {
    Name string
    Namespace string
}

type A struct {
    ObjectMeta
    X string
}

type B struct {
    ObjectMeta

    X string
}

func myfunc(v interface{}) ObjectMeta {
    switch u := v.(type) {
    case *A:
        return u.ObjectMeta
    case A:
        return u.ObjectMeta
    case *B:
        return u.ObjectMeta
    case B:
        return u.ObjectMeta
    }
    panic("No matching type")
}

func main() {
    fmt.Println(myfunc(&A{}))

    var v interface{} = &A{}
    fmt.Println(v.(*ObjectMeta))
}

ObjectMeta, A, B structs exist in external project. I have no control over them.

2条回答 默认 最新

相关推荐 更多相似问题