douqiao5314 2018-07-17 10: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 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:"-"`
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?