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

如何将不同类型的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.)

    1 打赏 评论

相关推荐 更多相似问题