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 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算