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?
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:"-"`
}