英文:
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.TypeOf
和type 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()
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论