【问题标题】:Type assertion with type from field of structure使用结构字段中的类型进行类型断言
【发布时间】: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)

标签: go types


【解决方案1】:

你可以这样试试。

func myLogic(i interface{}) {
    newVar2 = i.(Dog)
    fmt.Println(newVar2.Bark)
}

首先,将接口转换为 Dog 类型。 然后就可以从 Dog 类型(struct)中获取 Bark 值了

【讨论】:

    【解决方案2】:

    您正在寻找reflect

    例如下面的代码提取Dog.Bark的类型并检查输入变量是否具有相同的类型。

     package main
        
        import (
            "fmt"
            "reflect"
        )
        
        type Dog struct {
            Bark bool
        }
        
        func testtype(h interface{}) {
            d := Dog{}
            t := reflect.TypeOf(d.Bark)
    
            if reflect.TypeOf(h) == t {
                fmt.Println("success")
            } else {
                fmt.Println("failed")
            }
        }
    

    【讨论】:

    • 我尝试过反射,但在这里不起作用,因为 t 不被视为一种类型,当我尝试使用它输入断言时,它给了我以下错误“t 不是类型”= > i.(t)
    • reflect.TypeOf 无法做到这一点。我指的是您正在寻找的功能,即检查给定的interface{} 是否属于某种类型。不使用 bool 并仅使用原始结构及其成员来做到这一点。
    • 那你知道我怎么得到它吗?因为我的问题是如何获得可用于类型断言的类型
    • 使用上面的方法可以确保每次更改结构成员的类型时都不需要重新编写测试。
    猜你喜欢
    • 1970-01-01
    • 2020-04-12
    • 1970-01-01
    • 2020-10-30
    • 2018-12-14
    • 2019-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多