admin管理员组文章数量:1403352
I have a Person struct that implements an interface PersonInfo, which requires three getter methods: GetName(), GetEmail(), and GetLocation().
Two structs, Employee and Client, embed Person, but I need different GORM constraints on the Name field:
In Employee, Name should be varchar(100). In Client, Name should be varchar(50).
package main
import "fmt"
type PersonInfo interface {
GetName() string
GetEmail() string
GetLocation() string
}
type Person struct {
Name string `json:"name"`
Email string `json:"email"`
Location string `json:"location"`
}
func (p Person) GetName() string { return p.Name }
func (p Person) GetEmail() string { return p.Email }
func (p Person) GetLocation() string { return p.Location }
type Employee struct {
Person
Name string `json:"name" gorm:"type:varchar(100)"` // Overrides Person.Name
Salary int `json:"salary"`
}
func (e Employee) GetName() string { return e.Name } // Override for interface
type Client struct {
Person
Name string `json:"name" gorm:"type:varchar(50)"` // Overrides Person.Name
ServiceName string `json:"serviceName"`
}
func (c Client) GetName() string { return c.Name } // Override for interface
func PrintPersonInfo(p PersonInfo) {
fmt.Println("Name:", p.GetName())
fmt.Println("Email:", p.GetEmail())
fmt.Println("Location:", p.GetLocation())
}
func main() {
e := Employee{Name: "John Doe", Salary: 50000}
c := Client{Name: "Jane Doe", ServiceName: "Consulting"}
PrintPersonInfo(e)
PrintPersonInfo(c)
}
Questions:
Is overriding the Name field like this the best way to apply different GORM constraints while maintaining the PersonInfo interface?
Is there a cleaner or more idiomatic approach in Go to handle this situation?
Will this approach cause issues with GORM when saving Employee and Client to the database? Would appreciate any insights! Thanks in advance.
本文标签:
版权声明:本文标题:inheritance - How to Apply Different GORM Constraints on an Embedded Field While Implementing an Interface in Go? - Stack Overfl 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744386891a2603783.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论