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:

  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.

本文标签: