douqiao5314
2018-07-17 10:28 阅读 68

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 doushi3189 2018-07-17 10: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:"-"`
    }
    
    点赞 评论 复制链接分享

相关推荐