gpt4 book ai didi

go - 如何在golang中定义动态 "type struct"?

转载 作者:IT王子 更新时间:2023-10-29 01:49:40 24 4
gpt4 key购买 nike

这是 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 中的字段有一些相同的字段,但它们主要反射(reflect)数据库表(文档)并且它们属于同一类型(类型结构)。

当我在这一切面前说:

var model interface{}

我得到了错误:

type models.A is not an expression 

如果您问为什么,我这样做是为了避免代码中的代码冗余。

问题类似于:How to return dynamic type struct in 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。他们都有照片字段。

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

}

因为你唯一的区别是 var model models.Post/var models models.Product。这是代码中的冗余,它看起来很难看,但如果没有办法解决这个问题,那么好吧,我会用冗余完成这个。

最佳答案

您不能分配类型。您必须分配实例。您的代码实际上必须如下所示。我在您要更改的两行中添加了注释。

package main

import "fmt"

type B struct {
filed1 string
field2 string
//etc

}

type A struct {
filed1 string
field2 string
//etc

}

func main() {
var model interface{}
modelName := "b"
if modelName == "a" {
model = A{} // note the {} here
} else {
model = B{} // same here
}

fmt.Println(model)
}

尽管只是一个建议,您可能不想使用通用的 interface{} 类型,而最好使用既 AB 实现。通用的接口(interface)类型会让你更加头疼,并且真的违背了使用像 Go 这样的静态类型语言的目的。

关于go - 如何在golang中定义动态 "type struct"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36484427/

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