go - 使用结构字段中的类型进行类型断言

标签 go types

这是我努力的一个简化示例:

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/

相关文章:

scala - Scala 中具有依赖类型的参数的模式匹配的类型安全性

function - Haskell - 类型、枚举和函数

go - 在go中增加结构变量

html - 使用Golang的colly/goquery在html中查找文本

go - 如何将 swagger ui 与 golang 和 goa 集成

xml - 通过 UnMarshal 和 MarshalIndent 往返 xml

types - golang中的json-rpc,id为字符串

java - 在java中切换类型

python - 如何在异步 Python 函数中指定返回类型?

Python mypy 类型检查未按预期工作