簡體   English   中英

golang結構中tag的用途是什么?

[英]What is the use of tag in golang struct?

我不了解struct標簽的重要性。 我一直在尋找它們,並注意到它們可以與反射包一起使用。 但是我不知道它們的任何實際用途。

type TagType struct { // tags
    field1 bool   “An important answer”
    field2 string “The name of the thing”
    field3 int    “How much there are”
}

標簽的使用在很大程度上取決於結構的使用方式。

典型用途是為持久性或序列化添加規范或約束。

例如,當使用JSON解析器/編碼器時,當不使用默認編碼方案(即字段名稱)時,標簽用於指定如何從JSON讀取或以JSON寫入結構。

以下是json包文檔中的一些示例:

// Field is ignored by this package.
Field int `json:"-"`

// Field appears in JSON as key "myName".
Field int `json:"myName"`

// Field appears in JSON as key "myName" and
// the field is omitted from the object if its value is empty,
// as defined above.
Field int `json:"myName,omitempty"`

// Field appears in JSON as key "Field" (the default), but
// the field is skipped if empty.
// Note the leading comma.
Field int `json:",omitempty"`

使用的例子是JSON編碼/解碼中encoding/json

type TagType struct {
    field1 bool `json:"fieldName"`
    field2 string `json:",omitempty"`
}

文檔中的更多詳細信息: encoding / json

您還可以使用XML結構標簽,如下所示

type SearchResult struct {
    Title  string `xml:"title,attr"`
    Author string `xml:"author,attr"`
    Year   string `xml:"hyr,attr"`
    ID     string `xml:"owi,attr"`

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM