Empty or not required struct fields in golang

前端 未结 2 1562
温柔的废话
温柔的废话 2021-01-30 14:00

I\'m somewhat new to typed languages like Go and am trying to learn the best ways to implement things.

I have two structs that represent models that will be inserted in

2条回答
  •  误落风尘
    2021-01-30 14:16

    Avoid strut fields to marshal if they are empty -

    A struct field may be primitive type(string, int, bool etc) or even an another struct type.

    So sometimes we don't want a struct's field to go in json data(may to database insertion or in external api call) if they are empty

    Example:

    type Investment struct {
        Base
        Symbol string `json:"symbol" bson:"symbol" binding:"required"`
        Group  Group  `json:"group" bson:"group"`
        Fields bson.M `json:"fields" bson:"fields"`
    }
    

    If we want that Symbol and Group might contain empty values(0, false, nil pointer, zero size interface/struct) then we can avoid them in json marshaling like below.

    type Investment struct {
        Base
        Symbol string `json:"symbol,omitempty" bson:"symbol,omitempty" binding:"required"`
        Group  *Group  `json:"group,omitempty" bson:"group,omitempty"`
        Fields bson.M `json:"fields" bson:"fields"`
    }
    

    Her "Group" field is pointer to Group struct and whenever it will point to nil pointer it will be omitted from json marshaling.

    And obviously we would be filling values in Group field like below.

    // declared investment variable of type Investment struct
    
     investment.Group = &groupData
    

提交回复
热议问题