go - 如何将不同类型作为 struct{} 传递给 GoLang 函数?

标签 go struct types type-conversion parameter-passing

我想编写一个将不同结构类型作为 1 个参数的函数。此外,我必须确定,在这些结构中有一个 Id 字段。所以我想要这样的功能:

MyFunction(object *struct{ Id int })

我尝试将结构作为 *struct{ Id int }interface{} 参数传递。

例如,我有这两种结构类型:

type TableOne struct {
    Id   int
    name string
    date string
}

type TableTwo struct {
    Id      int
    address string
    athome  bool
}

要将它们保存在数据库中(使用反射),我有以下函数:

func SaveMyTables(tablename string, obj *struct{ Id int }) {
    // ... Some code here

    if obj.Id != 0 {
        // ... Some code here
    }

    // ... Some code here
}

我这样调用函数:

obj := &TableTwo{
    Id: 5
    address: "some address"
    athome: false
}

myPackage.Save("addresses", obj).

但是我得到这个错误:

cannot use obj (type *mytables.TableTwo) as type *struct { Id int } in argument to myPackage.Save

最佳答案

I want to write a function that takes different struct-types as 1 parameter. Also, I have to get sure, that in these struct is an Id field.

在当前版本的 Go 中,您无法执行此操作。 Go 支持将多个参数类型传递给单个参数的唯一方法是通过使用接口(interface),接口(interface)只能指定方法集,不能指定字段。

(Go 2 计划添加泛型,届时这可能是可能的。但是,尚无具体的时间线说明何时可用。)

关于go - 如何将不同类型作为 struct{} 传递给 GoLang 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56280025/

相关文章:

c++ - C++ 对象成员数组的默认初始化?

c - 在 C 中使用变量声明多个结构体

c++ - 如何将字符串转换为 uint32_t

c# - "is"运算符只是 "IsInstanceOfType"方法的语法糖

io - 如何将字节推送到 Go 中的读取器中?

go - 包装声明的目的是什么?

pointers - 我如何取消引用 Go 中的指针?

go - SSE2 从 golang 中的打包数据中提取 float

c - 头文件中的结构在源文件中产生错误

c# - 类型删除 : Java vs C#