这里是Playground链接https://play.golang.org/p/qMKxqrOcc2 。 问题类似于Playground上的问题。
比方说,我有一个条件,需要做到这一点:
if modelName == "a"{
model = models.A
}
else{
model = models.B
}
AB
type A struct{
filed1 string
field2 string
//etc
}
B
type B struct{
filed1 string
field2 string
//etc
}
AB
当我在所有的面前说:
var model interface{}
我得到错误:
type models.A is not an expression
如果你问为什么,我这样做是为了避免代码冗余。
这是代码更新:
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?
这里是新的更新
我有两个模型邮政和产品。 他们都有照片领域。
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.Productmodels.Post/var model models.Product