Go 更改接口的数据类型

Go 更改接口的数据类型,go,interface,Go,Interface,我试图确定传入接口的数据类型 然后使用该数据类型指定并声明一个新对象。下面是一个例子: func SomeFunction(ctx context.Context, records interface{}) (interface{}, error) { type objType = CustomStruct0 switch v := records.(type) { case CustomStruct1: fmt.

我试图确定传入接口的数据类型 然后使用该数据类型指定并声明一个新对象。下面是一个例子:

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)
但是,我得到的错误如下:类型CustomStruct1不是表达式。 正如所建议的,records对象可以是这4个接口/结构中的一个。 任何指导/指示都将不胜感激

我想要实现的是以下几点

从4个不同的位置调用SomeFunction()。 其中记录对象设置为4个不同的结构。 简单的解决方案是让4个SomeFunctions()接受调用者的确切数据类型。
但我只是想把所有这些结合在一起 并确定传入接口的数据类型,在此基础上,我可以初始化新对象并从eblow下面的结构中获取所需的属性

我理解这一点
objType=CustomStruct1
不正确,但我希望有办法 要将ObjType设置为开关块外部的默认类型,
然后根据datatype records接口is重新初始化ObjType。

下面是我的方法,使用go lang office的“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-------

正如错误所说,类型不是表达式,不能赋值,而且由于
recordsNew
类型必须在编译时已知,因此您无论如何都不能在运行时“assign”类型。
v
值已经声明为您想要的类型,但是,在switch语句中您不能做什么?我认为错误是“
CustomStruct0
不是表达式”,对吗?当您试图在此处使用
CustomStruct0
创建新变量时:
type objType=CustomStruct0
@user6304988,更高级别的目标仍然不清楚(至少对我来说)。也许它将有助于显示其中一种类型的代码。您只需将特定的逻辑放入swtich case语句中。否?要么您预先知道需要获取的属性,并且这些属性是共享的,因此您可以在之前声明一些变量,然后键入switch对象以分配这些变量并在以后使用它们,要么在需要的地方沿大块代码添加更多的type switch,或者,您可以重构这些类型以利用接口(我不是指空接口)。您也可以将类型作为字符串值进行切换,但它与常规类型切换相同。感谢您的回答,但这并不能真正回答我的问题。您的回答确实给出了records接口的类型,但这不是问题所在。不过,感谢您尝试作出响应。不过,我只是想离开您的sugg估计,这就是我想要的:在主记录中,type=someFunction(customStruct)recordsNew=records。(recordsType)fmt.Println(“name”,recordsNew.name)