最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

inheritance - How to Apply Different GORM Constraints on an Embedded Field While Implementing an Interface in Go? - Stack Overfl

programmeradmin2浏览0评论

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:

  1. Is overriding the Name field like this the best way to apply different GORM constraints while maintaining the PersonInfo interface?

  2. Is there a cleaner or more idiomatic approach in Go to handle this situation?

  3. Will this approach cause issues with GORM when saving Employee and Client to the database? Would appreciate any insights! Thanks in advance.

发布评论

评论列表(0)

  1. 暂无评论