golang Define struct once and use it in another struct definition

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

golang Define struct once and use it in another struct definition

问题

可以通过定义一个包含这些重复成员的结构体,并在其他结构体定义中使用它来减少冗余。例如:

type CommonMembers struct {
    Data bool `yaml:"data,omitempty" json:"data,omitempty"`
    Self bool `yaml:"self,omitempty" json:"self,omitempty"`
    Blob bool `yaml:"blob,omitempty" json:"blob,omitempty"`
}

type FormAction struct {
    CommonMembers
}

type ManifestSrc struct {
    CommonMembers
}

type PrefetchSrc struct {
    CommonMembers
}

通过将重复的成员定义在一个名为CommonMembers的结构体中,并在其他结构体中嵌入该结构体,可以避免重复定义相同的成员。这样做可以减少代码冗余,并提高代码的可维护性。

英文:

Define struct once and use it in another struct defination

type FormAction struct {
	Data bool `yaml:"data,omitempty" json:"data,omitempty"`
	Self bool `yaml:"self,omitempty" json:"self,omitempty"`
	Blob bool `yaml:"blob,omitempty" json:"blob,omitempty"`
}
type ManifestSrc struct {
	Data bool `yaml:"data,omitempty" json:"data,omitempty"`
	Self bool `yaml:"self,omitempty" json:"self,omitempty"`
	Blob bool `yaml:"blob,omitempty" json:"blob,omitempty"`
}
type PrefetchSrc struct {
	Data bool `yaml:"data,omitempty" json:"data,omitempty"`
	Self bool `yaml:"self,omitempty" json:"self,omitempty"`
	Blob bool `yaml:"blob,omitempty" json:"blob,omitempty"`
}

how we can reduce the redundancy of same members ?

答案1

得分: 1

可能是在多个结构体中定义相同字段而不重复自己的最典型方式是使用嵌入,因为它仍然允许你添加其他字段,例如:

type entity struct {
	Data bool `yaml:"data,omitempty" json:"data,omitempty"`
	Self bool `yaml:"self,omitempty" json:"self,omitempty"`
	Blob bool `yaml:"blob,omitempty" json:"blob,omitempty"`
}
type FormAction struct {
	entity
}
type ManifestSrc struct {
	entity
}
type PrefetchSrc struct {
	entity
	AnotherField string // 例如
}
英文:

Probably the most idiomatic way of defining the same fields in multiple structs without repeating yourself is to use embedding, because it still allows you to add other fields, eg:

type entity struct {
	Data bool `yaml:"data,omitempty" json:"data,omitempty"`
	Self bool `yaml:"self,omitempty" json:"self,omitempty"`
	Blob bool `yaml:"blob,omitempty" json:"blob,omitempty"`
}
type FormAction struct {
	entity
}
type ManifestSrc struct {
	entity
}
type PrefetchSrc struct {
	entity
	AnotherField string // For example
}

huangapple
  • 本文由 发表于 2021年11月24日 19:23:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/70095199.html
匿名

发表评论

匿名网友

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

确定