登录
首页 >  Golang >  Go问答

在 Golang 中将其设置为接口后如何恢复结构类型

来源:stackoverflow

时间:2024-04-15 16:42:35 243浏览 收藏

从现在开始,努力学习吧!本文《在 Golang 中将其设置为接口后如何恢复结构类型》主要讲解了等等相关知识点,我会在golang学习网中持续更新相关的系列文章,欢迎大家关注并积极留言建议。下面就先一起来看一下本篇正文内容吧,希望能帮到你!

问题内容

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

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


解决方案


以下是如何使用 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)
        }
    }
}

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>