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.