Reputation: 2487
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?
Upvotes: 1
Views: 454
Reputation: 20703
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.
Upvotes: 2