Go 如何制作函数的参数是一个";“通用”;结构
例如,我想写一个这样的方法:Go 如何制作函数的参数是一个";“通用”;结构,go,struct,Go,Struct,例如,我想写一个这样的方法: func parseData(rawData []json.RawMessage) []interface{} { var migrations []interface{} for _, migration := range rawData { // this is an custom struct command := UserCommand{} json.Unmarshal(migration, &
func parseData(rawData []json.RawMessage) []interface{} {
var migrations []interface{}
for _, migration := range rawData {
// this is an custom struct
command := UserCommand{}
json.Unmarshal(migration, &command)
migrations = append(migrations, command)
}
return migrations
}
这段代码的问题是:如果我不想解析UserCommand
,而想解析任何其他代码,比如ProductCommand
,我必须编写相同的代码,只是在第行:command:=UserCommand{}
不同。所以我的问题是:我怎样才能泛化这段代码
我尝试过此解决方案,但不起作用:
func parseData(rawData []json.RawMessage, class interface{}) []interface{} {
var migrations []interface{}
for _, migration := range rawData {
command := class
json.Unmarshal(migration, &command)
migrations = append(migrations, command)
}
return migrations
}
// then I call this method
parseData(data, UserCommand{})
但它不起作用。它返回map[string]接口{}
的数组,如何修复此问题
编辑:
下面是一些我定义的结构
type UserCommand struct {
User string
Info string
}
type ProductCommand struct {
Name string
Quanlity int
}
通过使用Go的包,可以支持这种“通用”签名样式
输出显示第一个parseData
调用解析了两个UserCommand
结构,第二个调用解析了两个ProductCommand
结构
[]interface {}{main.UserCommand{User:"u1", Info:"i1"}, main.UserCommand{User:"u2", Info:"i2"}}
[]interface {}{main.ProductCommand{Name:"n1", Quantity:1}, main.ProductCommand{Name:"n2", Quantity:2}}
通过使用Go的包,可以支持这种“通用”签名样式
输出显示第一个parseData
调用解析了两个UserCommand
结构,第二个调用解析了两个ProductCommand
结构
[]interface {}{main.UserCommand{User:"u1", Info:"i1"}, main.UserCommand{User:"u2", Info:"i2"}}
[]interface {}{main.ProductCommand{Name:"n1", Quantity:1}, main.ProductCommand{Name:"n2", Quantity:2}}
有人投了反对票。请给我解释一下原因。因为我是围棋新手,在问这个问题之前,我已经尝试了尽可能多的解决方案。我不能代表最初的投票,但我发现这个问题不清楚。什么是
ProductCommand
?什么是类
?如果这是您想要的,为什么不直接解组到类中呢?在第二个示例中,您要解组的类型是*接口{}
,因此接口{}
使用的有文档记录的默认类型是map[string]接口{}
@JimB,我已经在代码中添加了UserCommand
和ProductCommand
。谢谢你的观点。因为我是围棋新手,所以我只是使用所有的方法:(所以正如你指出的,这真的没有意义。你能用一般的方法来做吗?@TrầnKimDự 你如何决定要解组到哪种类型?有人投了反对票。请为我解释原因。因为我是围棋新手,在问这个问题之前,我已经尝试了尽可能多的解决方案。不能代表最初的投票,但我发现问题不清楚。什么是ProductCommand
?什么是class
?为什么不直接解组如果这是您想要的,请将其放入class
?在第二个示例中,您要解组的类型是*接口{}
,因此用于接口{}
的有文档记录的默认类型是映射[string]接口{}
@JimB我已经在我的代码中添加了UserCommand
和ProductCommand
。谢谢你的观点。因为我是围棋新手,所以我只是使用所有的方法:(正如你指出的,这真的没有意义。你能用一般的方法来做吗?@TrầnKimDự 您如何决定解组到哪种类型?以及
[]interface {}{main.UserCommand{User:"u1", Info:"i1"}, main.UserCommand{User:"u2", Info:"i2"}}
[]interface {}{main.ProductCommand{Name:"n1", Quantity:1}, main.ProductCommand{Name:"n2", Quantity:2}}