golang struct 优化

type (

    Sale struct {
        BaseModel
        WareroomID int      `json:"wareroom_id"`
        ProductID  int      `json:"product_id"`
        Quantity   int      `json:"quantity"`
    }

    SaleLink struct {
        BaseModel
        WareroomID int      `json:"wareroom_id"`
        ProductID  int      `json:"product_id"`
        Quantity   int      `json:"quantity"`
        Product    Product  `json:"product"`
        Wareroom   Wareroom `json:"wareroom"`
    }
)

有时候在返回接口的时候 ,有时候不希望返回 关联表 ProductWareroom , 有时候又需要, 所以定义了 2 个 struct , 感觉这样写 好啰嗦, 想请大佬 指导一下, 该如何只优化 这个 struct, 其他代码不用动呢?

求大佬 指导一下 ????

阅读 3.1k
2 个回答
  • embed,这很go
 type (

    Sale struct {
        BaseModel
        WareroomID int      `json:"wareroom_id"`
        ProductID  int      `json:"product_id"`
        Quantity   int      `json:"quantity"`
    }

    SaleLink struct {
        Sale
        Product    Product  `json:"product"`
        Wareroom   Wareroom `json:"wareroom"`
    }
)
  • 序列化函数,最符合func的初衷
func (sl *SaleLink) LinkJson []byte {
    return 把字段都加上,然后`Marshal`
}
func (sl *SaleLink) Json []byte {
    return 部分字段,然后`Marshal`
}
  • 表现类,这很设计模式
//通过sale构建下面这两个类,分别展现`json`
type LinkSaleVO struct {
}
type SaleVO struct {
}
type SaleLink struct {
    BaseModel
    WareroomID int      `json:"wareroom_id"`
    ProductID  int      `json:"product_id"`
    Quantity   int      `json:"quantity"`
    Product    Product  `json:"product,omitempty"`
    Wareroom   Wareroom `json:"wareroom,omitempty"`
}

加上omitempty,如果你不给struct赋上这两个值,json序列化的时候,就不会有这两个字段

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题