这是我努力的一个简化示例:
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 以便将其用于类型断言?
最佳答案
你可以这样试试。
func myLogic(i interface{}) {
newVar2 = i.(Dog)
fmt.Println(newVar2.Bark)
}
首先,将接口(interface)转换为 Dog 类型。然后您可以从 Dog 类型(结构)中获取 Bark 值
关于go - 使用结构字段中的类型进行类型断言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63269555/