【问题标题】:How do i recover the struct type after make it as Interface in Golang在Golang中将其作为接口后如何恢复结构类型
【发布时间】:2020-06-11 10:14:56
【问题描述】:

我想将一些类似的 func 代码合并到一个 func 中,但是每个旧 func 都使用不同类型的结构,所以我打算通过不同类型的字符串创建模型。 所以我做这样的事情:

type A struct {
   filed string
}
type B struct {
   filed string
}
and still C, D, E, F here...(every struct has its own method different with others)

我想在一个地方创建这些类型:

create(typeName string) interface {
   switch typeName {
   case A:
       return &A{}
   case B:
       return &B{}
   ....(more case than 10 times)
   }
}

然后我在这里使用 create():

model := create("A")

现在model是接口类型,没有A的文件,怎么简单恢复模型类型为A

【问题讨论】:

标签: go


【解决方案1】:

这是一个示例,说明如何使用 type assertion 将接口转换为底层结构

这里e 是结构类型,因此您可以访问它的任何字段或结构方法。

package main

import (
    "fmt"
)

type A struct {
    AF int
}

type B struct {
    BF string
}

func main() {
    ds := []interface{}{
        A{1},
        B{"foo"},
    }

    for _, d := range ds {
        switch e := d.(type) {
        case A:
            fmt.Println(e.AF)
        case B:
            fmt.Println(e.BF)
        }
    }
}

【讨论】:

  • 感谢您的帮助。有没有办法避免使用type assertion,有太多的开关/案例并破坏了原始逻辑。我希望我可以像原始类型一样使用Model
  • 很遗憾,没有其他办法。您为抽象支付的费用与实际成本一样多。
猜你喜欢
  • 2020-03-31
  • 2016-01-10
  • 1970-01-01
  • 2017-11-29
  • 2016-10-15
  • 1970-01-01
  • 2015-09-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多