【发布时间】:2020-08-05 16:31:32
【问题描述】:
以下是我遇到的问题的简化示例:
type Dog struct {
Bark bool
}
func myLogic(i interface{}) {
newVar = i.(Dog) // Work fines -> newVar is of type Dog if I passed such type to the function through the interface
newVar2 = i.(Dog.Bark) // I get an error "type Dog has no method Bark"
}
我怎样才能通过 Dog 结构从 Bark 字段中获取 bool 类型,以便将其用于类型断言??
【问题讨论】:
-
Dog是一个类型,Bark是一个成员,而不是一个类型。 -
大家好,我可能没有充分解释我想做的事情。我不想访问 Bark 方法,我想访问 Bark 类型,这样如果我在某个地方更改一些复杂的模型,我的代码就不必更改类型断言。总之,我想做 i.(Dog.Bark) 而不是 i.(bool)