在go中动态调用模型 [英] calling model dynamically in go

查看:79
本文介绍了在go中动态调用模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑诸如牛仔裤,衬衫,短裤之类的产品,我想将订单存储在相应的产品表中,例如与牛仔裤相关的订单应存储在牛仔裤表中,依此类推.每个表将具有相同的参数.因此,在将订单存储在表中时,我应该能够调用相应的结构并存储订单. 我来自Laravel(PHP)背景,可以在其中加载动态模型,例如

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";

但是在Go语言中,如果调用动态struct怎么办

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

例如,

在ABC.go模型中

type ABC struct{
  Name string
  Invetory int
}

在XYZ.go模型中

type XYZ struct {
  Name string
  Invetory int
}

所以输入可能是ABC或XYZ,我必须相应地加载该结构.

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

加载结构ABC

inpt := "ABC"

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

以上代码段中的模型名称是动态的.我们如何在Go中做到这一点?

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

推荐答案

请勿尝试将其他语言的方法和编程模式移植到Go中-这将使您的生活变得更加艰难,而在最糟糕的情况下也会流泪.

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.

您可以执行以下操作:

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.

这篇关于在go中动态调用模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆