【发布时间】: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