Go 使用接口作为参数避免代码重复
我在另一个结构上有多个具有公共关系的结构Go 使用接口作为参数避免代码重复,go,optimization,struct,interface,Go,Optimization,Struct,Interface,我在另一个结构上有多个具有公共关系的结构 type Question struct { ID int `json:"id,omitempty"` ... } type EvaluationQuestion struct { Question Question `json:"question" sql:"-"` Min int `json:"min"` Max int `json:"max"`
type Question struct {
ID int `json:"id,omitempty"`
...
}
type EvaluationQuestion struct {
Question Question `json:"question" sql:"-"`
Min int `json:"min"`
Max int `json:"max"`
QuestionID int `json:"question_id,omitempty"`
}
type TextQuestion struct {
Question Question `json:"question" sql:"-"`
MaxValue int `json:"max_value"`
QuestionID int `json:"question_id,omitempty"`
}
我还有一个方法可以在数据库中保存数据,每个结构都是相同的,只有结构类型会改变
func CreateTextQuestion(textQuestion *TextQuestion) error {
question := textQuestion.Question
if err := database.Db.Insert(&question); err != nil {
return err
}
textQuestion.QuestionID = question.ID
return database.Db.Insert(textQuestion)
}
为了避免代码重复,我尝试使用将为每个结构实现方法的接口(即使也有一些重复…)
然后我更新了我的Create
方法来使用这个界面
func Create(entity Entity) error {
question := entity.getQuestion()
if err := database.Db.Insert(&question); err != nil {
return err
}
questionType := entity.questionID(question.ID)
return database.Db.Insert(&questionType)
}
问题是我的接口与每个结构都不兼容,因此我会出现编译错误,因为我的questionID
方法的预期返回类型不正确
api_1 |[00]处理程序/choiceQuestion.go:28:39:无法将问题(type models.choiceQuestion)转换为类型模型。实体:
api_1 |[00]models.ChoiceQuestion未实现models.Entity(models.questionID方法的类型错误)
api_1 |[00]有模型。问题ID(int)模型。选择问题
api_1 |[00]想要模型。问题ID(int)模型。文本问题
使用Go处理多个结构时,有没有避免代码重复的方法
我还尝试了类型切换和反射,但没有成功。对每个接口函数使用相同的类型。@Flimzy Ok我返回一个
接口{}
,这是工作的,对每个接口函数使用相同的类型。@Flimzy Ok我返回一个接口{}
,这是工作的
func Create(entity Entity) error {
question := entity.getQuestion()
if err := database.Db.Insert(&question); err != nil {
return err
}
questionType := entity.questionID(question.ID)
return database.Db.Insert(&questionType)
}