calling model dynamically in go

混江龙づ霸主 提交于 2019-12-14 03:04:46

问题


Consider products like jeans, shirts, shorts and I want to store the orders in respective product tables for eg jeans related order should get stored in jeans tables and so on. Every table would have identical parameters. So while storing orders in table I should be able to call the respective struct and store the order. I am coming from Laravel (PHP) background where I can load dynamic model like

$model = "Dynamic passed model names"

$class = "App\\Models\\$model";

but in Go how can we do that if call dynamic struct

e.g,

in model ABC.go

type ABC struct{
  Name string
  Invetory int
}

in model XYZ.go

type XYZ struct {
  Name string
  Invetory int
}

So input could be ABC or XYZ and I have to load the struct accordingly.

load the struct ABC

inpt := "ABC"

product := models.<inpt>{
  Name: "prodct name"
  Inventory: 10
}

Above snippet the model name is dynamic. How can we do this in Go?


回答1:


Do not try to port methods and programming patterns from other languages to Go - it will make your life harder at best and will end in tears at worst.

You can do something like:

type Inventory interface{
 // Your interface defining methods here
}

var toUse Inventory

switch input {
case "ABC":
   toUse = ABC{}
case "XY":
   toUse = XY{}
}

The question is why you have two types which are (aside from a typo) exactly identical.



来源:https://stackoverflow.com/questions/58889672/calling-model-dynamically-in-go

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!