gpt4 book ai didi

go - go中动态调用模型

转载 作者:行者123 更新时间:2023-12-03 00:31:00 26 4
gpt4 key购买 nike

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

$model = "Dynamic passed model names"

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

但是在 Go 中,如果调用动态结构体,我们该如何做到这一点

例如,

在模型 ABC.go 中

type ABC struct{
Name string
Invetory int
}

在模型 XYZ.go 中

type XYZ struct {
Name string
Invetory int
}

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

加载结构体ABC

inpt := "ABC"

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

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

最佳答案

不要尝试将其他语言的方法和编程模式移植到 Go - 这最多只会让你的生活变得更加困难,最坏的情况下会以泪水告终。

你可以这样做:

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

var toUse Inventory

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

问题是为什么你有两个完全相同的类型(除了拼写错误之外)。

关于go - go中动态调用模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58889672/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com