【问题标题】:How to pass different types as struct{} to function in GoLang?如何将不同类型作为 struct{} 传递给 GoLang 中的函数?
【发布时间】:2019-10-10 07:28:55
【问题描述】:

我想编写一个将不同结构类型作为 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
}

要将它们保存在数据库中(使用reflection),我有以下功能:

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

【问题讨论】:

  • Go 是一种严格类型的语言。如果为参数指定结构类型,那就是必须传递的类型,确切地
  • @Adrian,我明白了。因此,除了使用其他 agrument 类型多次实现完全相同的功能外,别无他法?这正是我想要阻止的。
  • 您说您尝试在 interface{} 中传递值。那是正确的方法,什么不起作用?
  • @JimB 我必须确保该结构有一个Id int 变量,因为@if obj.Id != 0 { Golang 需要知道该变量在那里。 interface{ Id int } 也不起作用。
  • 你不能。没有办法在字段上签订合同。一个接口提供了一个关于行为的契约(它应该如此)。设计需要从头开始修正。

标签: go struct types type-conversion parameter-passing


【解决方案1】:

我想编写一个将不同结构类型作为 1 个参数的函数。另外,我必须确定,在这些结构中是一个 Id 字段。

在当前版本的 Go 中,你不能这样做。 Go 支持将多个参数类型传递给单个参数的唯一方法是通过使用接口,接口只能指定方法集,不能指定字段。

(Go 2 计划添加泛型,届时这可能是可能的。但是,没有具体的时间表来说明何时可用。)

【讨论】:

    猜你喜欢
    • 2015-04-04
    • 2016-02-28
    • 2018-01-02
    • 1970-01-01
    • 2023-04-02
    • 2020-02-06
    • 1970-01-01
    • 2018-10-30
    • 1970-01-01
    相关资源
    最近更新 更多