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 labview程序设计
  • ¥15 为什么在配置Linux系统的时候执行脚本总是出现E: Failed to fetch http:L/cn.archive.ubuntu.com
  • ¥15 Cloudreve保存用户组存储空间大小时报错
  • ¥15 伪标签为什么不能作为弱监督语义分割的结果?
  • ¥15 编一个判断一个区间范围内的数字的个位数的立方和是否等于其本身的程序在输入第1组数据后卡住了(语言-c语言)
  • ¥15 游戏盾如何溯源服务器真实ip?
  • ¥15 Mac版Fiddler Everywhere4.0.1提示强制更新
  • ¥15 android 集成sentry上报时报错。
  • ¥50 win10链接MySQL
  • ¥15 抖音看过的视频,缓存在哪个文件