在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問(wèn)答/GO  網(wǎng)絡(luò)安全/ golang struct 優(yōu)化

golang struct 優(yōu)化

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"`
    }
)

有時(shí)候在返回接口的時(shí)候 ,有時(shí)候不希望返回 關(guān)聯(lián)表 ProductWareroom , 有時(shí)候又需要, 所以定義了 2 個(gè) struct , 感覺(jué)這樣寫(xiě) 好啰嗦, 想請(qǐng)大佬 指導(dǎo)一下, 該如何只優(yōu)化 這個(gè) struct, 其他代碼不用動(dòng)呢?

求大佬 指導(dǎo)一下 ????

回答
編輯回答
夕顏
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賦上這兩個(gè)值,json序列化的時(shí)候,就不會(huì)有這兩個(gè)字段

2017年4月1日 23:05
編輯回答
清夢(mèng)
  • 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"`
    }
)
  • 序列化函數(shù),最符合func的初衷
func (sl *SaleLink) LinkJson []byte {
    return 把字段都加上,然后`Marshal`
}
func (sl *SaleLink) Json []byte {
    return 部分字段,然后`Marshal`
}
  • 表現(xiàn)類,這很設(shè)計(jì)模式
//通過(guò)sale構(gòu)建下面這兩個(gè)類,分別展現(xiàn)`json`
type LinkSaleVO struct {
}
type SaleVO struct {
}
2018年9月16日 00:23