这里是 Playground 链接 https://play.golang.org/p/qMKxqrOcc2。问题与 Playground 上的一个类似。
假设我有一个条件,需要执行以下操作:
我收到了一个错误信息:
我这样做是为了避免代码冗余,如果您问我为什么。
问题类似于此:如何在Golang中返回动态类型结构体? 以下是更新的代码:
现在我需要一个函数,它应该返回以下内容:
假设我有一个条件,需要执行以下操作:
if modelName == "a"{
model = models.A
}
else{
model = models.B
}
其中A
和B
是一些模型:
type A struct{
filed1 string
field2 string
//etc
}
模型B
是
type B struct{
filed1 string
field2 string
//etc
}
A
和 B
中的字段有一些相同,但大多数反映了数据库表(文档),并且它们是相同类型(结构体类型)。
当我在所有人面前说:
var model interface{}
我收到了一个错误信息:
type models.A is not an expression
我这样做是为了避免代码冗余,如果您问我为什么。
问题类似于此:如何在Golang中返回动态类型结构体? 以下是更新的代码:
b := c.mainHelper.GetModelBy("id", id, modelName).(map[string]interface{})
mapstructure.Decode(b, &model)
if modelName == "a"{
model.Photos = []string{"ph1","ph2"}
}
if modelName == "b"{
model.Docs = []string{"doc1","doc2"}
}
c.mainHelper.UpdateModel(product, id, modelName)
我知道这很愚蠢,也可能无法实现,但有没有办法做到这一点:
var model models.modelName --> somehow to concat modelName to this models?
这里有新的更新
我有两个模型:Post和Product。它们都有Photos字段。
type Post struct{
Photos []string
//etc
}
type Product {
Photos []string
//
}
现在我需要一个函数,它应该返回以下内容:
func () RemovePhotos(id string, modelName string){
//if modelName=="post"
//get model post with id
//if modelName=="product"
//get model product with id
//set model.Photos = []string
//update model in db
}
我理解无法分配类型,但如何使用此函数从不同类型中删除数据?据我所见,代码冗余将如下所示:
func () RemovePhotos(id string, modelName string) return bool{
if modelName == "post"{
var model models.Post
modelWithdata := getModelWithId.(*model)
modelWithdata.Photos = []string
//update model in db here
}
if modelName == "product"{
var model models.Product
modelWithdata := getModelWithId.(*model)
modelWithdata.Photos = []string
//update model in db here
}
//it does not matter what I return this is just redundancy example
return true
}
你只需要关注变量模型的差异,即models.Post/var model models.Product
。
这种代码冗余看起来不美观,但如果没有其他办法,那么好吧,我会接受这种带有冗余的代码。
model
将如何使用?最佳解决方案将取决于此。 - Brian