【发布时间】:2020-10-12 07:24:42
【问题描述】:
我是新手,在访问运行时未知的结构数据时遇到问题:
type Nested struct {
Value string
}
type TypeA struct {
Nested
Foo string
}
type TypeB struct {
Nested
Bar string
}
我必须实现以下回调:
func Callback(param interface{}) {
}
param 可以是*TypeA 或*TypeB。
如何转换类型转换/转换param,以便我可以访问这两种类型共有的已知Nested 元素?
因为接口是隐式实现的,我想我可以做这样的事情
type Whatever struct {
Nested
}
然后
func Callback(param interface{}) {
nst := param.(*Whatever)
fmt.Printf(nst.Nested.Value)
}
然而这会导致
interface {} is *misc.TypeA, not *misc.Whatever
提前感谢您的帮助。
【问题讨论】:
标签: go type-conversion