douqiao5314 2018-07-17 02:28
浏览 88
已采纳

Golang未设置结构字段

In Golang, I have below Struct with three fields

type Person struct {
   name string
   age  int
   rank int
}

For Processing, I need a rank field, but for output, I want to exclude the rank field from struct as I am directly passing above struct to JSON encoder to throw a response.

Is there any way by which I can unset rank field from Struct?

  • 写回答

1条回答 默认 最新

  • doushi3189 2018-07-17 02:31
    关注

    To unset a field, assign its zero value to it, like:

    var p Person
    p.rank = 0
    

    Also know that if you want to use Person to work with JSON, you have to export the fields, unexported fields are not processed by the encoding/json package, so change Person to:

    type Person struct {
        Name string
        Age  int
        rank int
    }
    

    This alone will make rank left out from JSON processing, as it is unexported.

    If you need to export the rank field too, then use the json:"-" tag value to exclude an exported field from JSON processing:

    type Person struct {
        Name string
        Age  int
        Rank int `json:"-"`
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部