douyun3631 2019-05-23 17:08
浏览 230
已采纳

如何将不同类型的struct {}传递给GoLang?

I want to write a function that takes different struct-types as 1 parameter. Also, i have to get sure, that in these struct ist a Id field. so i want to have a function like this: MyFunction(object *struct{ Id int }

I have tried it with passing the struct to a *struct{ Id int } and to a interface{} parameter.

For example, i have these 2 struct-types:

type TableOne struct {
    Id   int
    name string
    date string
}

type TableTwo struct {
    Id      int
    address string
    athome  bool
}

To save them in the database (using reflection) i have the following function:

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

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

    // ... Some code here
}

I will call the function like this:

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

myPackage.Save("addresses", obj).

But i get this error:

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

1条回答 默认 最新

  • duanjin9035 2019-05-26 10:00
    关注

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

    As of the current version of Go, you cannot do this. The only way Go supports passing multiple argument types to a single parameter is through the use of interfaces, and interfaces can only specify method sets, not fields.

    (Go 2 plans to add generics, and this may be possible then. However, there's no concrete timeline for when that will be available.)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 手机连接电脑热点显示无ip分配
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大