登录
首页 >  Golang >  Go问答

修改数据接口的类型

来源:stackoverflow

时间:2024-03-24 22:24:36 448浏览 收藏

本文探讨了在 Go 中确定传入接口数据类型的方法。作者最初尝试使用 switch 语句,但遇到了错误。随后,作者提供了使用“reflect”库的解决方案,该库可以检查变量的类型。在提供的示例中,SomeFunction 函数使用 fmt.Sprintf 将接口类型转换为字符串,然后将其与已知结构的类型进行比较。如果匹配,则函数会打印相应的结构名称,否则会返回错误。

问题内容

我正在尝试确定传入接口的数据类型是什么 然后分配声明具有该数据类型的新对象。示例如下:

func SomeFunction(ctx context.Context, records interface{}) (interface{}, error) {
        type objType = CustomStruct0
    
        switch v := records.(type) {
        case CustomStruct1:
            fmt.Println("-----CustomStruct1-------")
            objType = CustomStruct1
        case CustomStruct2:
            fmt.Println("-----CustomStruct2-------")
            objType = CustomStruct2
        case CustomStruct3:
            fmt.Println("-----CustomStruct3-------")
            objType = CustomStruct3
        default:
            return nil, fmt.Errorf("data type not recognized")
        }

    recordsNew = i.(objType)
    fmt.Println("records in recordsNew:", recordsNew)

但是我得到的错误如下: type customstruct1 不是表达式。 正如所建议的,记录对象可以是这 4 个接口/结构之一。 任何指导/指示将不胜感激。

我想要实现的目标如下

somefunction() 从 4 个不同的地方被调用。 其中记录对象设置为 4 个不同的结构。 简单的解决方案是让 4 somefunctions() 接受来自调用者的确切数据类型。

但我只是试图将所有这些合二为一 并确定传入接口的数据类型是什么,基于此,我可以初始化新对象并从下面的这些结构中获取我需要的属性。

我明白设置这个 objtype = customstruct1 不正确,但我希望有办法 将 objtype 设置为 switch 块之外的默认类型, 然后根据接口的数据类型记录重新初始化objtype。


解决方案


以下是我的方法,使用go lang办公室的“reflect”库,只需在您想检查变量的类型时解决问题即可:

package main

import (
    "fmt"
    "reflect"
)

type CustomStruct1 struct {
}

type CustomStruct2 struct {
}

type CustomStruct3 struct {
}

func main() {
    var customStruct1 CustomStruct1
    SomeFunction(customStruct1)
}

func SomeFunction(records interface{}) (interface{}, error) {
    switch fmt.Sprintf("%s", reflect.TypeOf(records)) {
    case "main.CustomStruct1":
        fmt.Println("-----CustomStruct1-------")
    case "main.CustomStruct2":
        fmt.Println("-----CustomStruct2-------")
    case "main.CustomStruct3":
        fmt.Println("-----CustomStruct3-------")
    default:
        fmt.Println("-----Unrecognized Struct-------")
        return nil, fmt.Errorf("data type not recognized")
    }

    return records, nil
}
==========
$ go run main.go
-----CustomStruct1-------

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《修改数据接口的类型》文章吧,也可关注golang学习网公众号了解相关技术文章。

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