简体   繁体   English

Golang未设置结构字段

[英]Golang unset Struct Field

In Golang, I have below Struct with three fields 在Golang中,我在Struct下面有三个字段

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. 对于Processing,我需要一个rank字段,但是对于输出,我想从struct中排除rank字段,因为我直接将struct上面的内容传递给JSON编码器以引发响应。

Is there any way by which I can unset rank field from Struct? 有什么方法可以取消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: 还知道,如果要使用Person来处理JSON,则必须导出字段,未导出的字段不会由encoding/json包处理,因此将Person更改为:

type Person struct {
    Name string
    Age  int
    rank int
}

This alone will make rank left out from JSON processing, as it is unexported. 由于未导出,仅此一项将使rank从JSON处理中遗漏。

If you need to export the rank field too, then use the json:"-" tag value to exclude an exported field from JSON processing: 如果您还需要导出rank字段,请使用json:"-"标记值从JSON处理中排除导出的字段:

type Person struct {
    Name string
    Age  int
    Rank int `json:"-"`
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM