可以将相同的结构体用于gorm和json吗?

huangapple go评论70阅读模式
英文:

Is it possible to use same struct for gorm as well as json?

问题

这将起作用吗?
这是允许的吗?

英文:
type Student struct {
     name string `gorm:"fullname"` `json:"student_name"`
}

Will this work?
Is this allowed?

答案1

得分: 2

没有问题,因为gorm和json使用不同的标签名称,所以是允许的。

英文:

There is no problem, it is allowed as gorm and json use different tag name

答案2

得分: 0

交付数据类型和实体数据类型强烈建议保持分开。

但你能做到吗? 是的。它有效吗? 是的。这是一个快速解决方案吗? 绝对是。

以下是一些问题,如果需要将它们保留在一个结构中,需要回答:

  1. 如果向数据模型添加额外字段会发生什么?
  2. 其他开发人员是否被告知了这个决定?
  3. 你是否愿意以后耗费时间进行重构?

但在我看来,正确的做法是将模型分开,并使用映射函数进行转换。

英文:

Delivery data types and entity data types are highly recommended to be kept separate.
But can you do it? Yes. Does it work? Yes. Is it quick solution? Absolutely

Here is some question to answer if it is needed to be kept in one struct :

  1. What happens if you add additional field to your data model?
  2. Are others developers warned about this decision?
  3. Are you okay with later time consuming refactoring?

But correct way to do it in my opinion is to separate models and convert them using mapper function.

huangapple
  • 本文由 发表于 2021年8月11日 10:44:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/68735406.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定