具有多个映射符号的结构体

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

structs with multiple mapping notations

问题

我有这两个结构体,它们表示相同的实体(一个来自Json文件,另一个来自数据库):

type DriverJson struct {
    ID   int    `json:"id"`
    Name string `json:"name"`
}

type DriverOrm struct {
    ID   int    `orm:"column(id);auto"`
    Name string `orm:"column(name);size(255);null"`
}

我想将它们合并成一个Driver结构体,如何合并映射注释(orm:,json:)?

谢谢。

英文:

I have these two structs which represent the same entities (one comes from a Json file and the other from a DB)

type DriverJson struct {
	ID            int    `json:"id"`
	Name          string `json:"name"`
}

type DriverOrm struct {
	ID            int       `orm:"column(id);auto"`
	Name          string    `orm:"column(name);size(255);null"`
}

I want to merge them into one Driver struct, how do I merge the mapping notations (orm:, json:)?

Thank you

答案1

得分: 4

reflect.StructTag文档中所述,按照惯例,标签字符串的值是由空格分隔的key:"value"对,因此可以简单地写成:

type DriverJson struct {
    ID   int    `json:"id" orm:"column(id);auto"`
    Name string `json:"name" orm:"column(name);size(255);null"`
}

详情请参阅 https://stackoverflow.com/questions/10858787/what-are-the-uses-for-tags-in-go/30889373#30889373

英文:

As mentioned in the documentation of reflect.StructTag, by convention the value of a tag string is a space-separated key:"value" pairs, so simply:

type DriverJson struct {
    ID   int    `json:"id" orm:"column(id);auto"`
    Name string `json:"name" orm:"column(name);size(255);null`
}

For details, see https://stackoverflow.com/questions/10858787/what-are-the-uses-for-tags-in-go/30889373#30889373

huangapple
  • 本文由 发表于 2017年1月11日 20:07:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/41590571.html
匿名

发表评论

匿名网友

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

确定