如何检查外部类型是否是内部类型的一种类型?

huangapple go评论83阅读模式
英文:

How do I check if a outer type is a type of inner type?

问题

如果我在应用程序中传递不同形式的用户结构体,有没有办法检查嵌入的结构体是否是外部结构体的类型?

type (
    user struct {
        name  string
        email string
    }
    admin struct {
        user
        level string
    }
)
英文:

If I have different forms of user structs being passed around my application is there a way to check if that embedded struct is a type of the outer struct?

type (
    user struct {
        name  string
        email string
    }
    admin struct {
        user
        level string
    }
)

答案1

得分: 1

根据您的需求,您有两种主要方法:reflect.TypeOftype switch

您可以使用第一种方法来比较接口的类型与另一个类型。示例:

if reflect.TypeOf(a) == reflect.TypeOf(b) {
    doSomething()
}

您可以使用第二种方法根据接口的类型执行特定的操作。示例:

switch a.(type) {
    case User:
        doSomething()
    case Admin:
        doSomeOtherThing()
}
英文:

Depending on you need, you have two main methods: reflect.TypeOf, and the type swtich.

You will use the first to compare the type of an interface with another one. Example:

if reflect.TypeOf(a) == reflect.TypeOf(b) {
    doSomething()
}

You will use the second to do a particular action given the type of an interface. Example:

switch a.(type) {
    case User:
        doSomething()
    case Admin:
        doSomeOtherThing()
}

huangapple
  • 本文由 发表于 2015年3月14日 01:17:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/29038269.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定