5

看看在这里找到的这个片段

进口 (
    “编码/xml”
    “fmt”
    “操作系统”
)

功能主要(){
    类型地址结构{
        城市,州字符串
    }
    类型人结构{
        XMLName xml.Name `xml:"person"`
        ID int `xml:"id,attr"`
        名字字符串 `xml:"name>first"`
        姓氏字符串 `xml:"name>last"`
        年龄int`xml:“年龄”`
        高度 float32 `xml:"height,omitempty"`
        已婚布尔
        地址
        注释字符串`xml:",comment"`
    }

    v := &Person{Id: 13, FirstName: "John", LastName: "Doe", Age: 42}
    v.Comment = "需要更多细节。"
    v.Address = 地址{“Hanga Roa”、“复活节岛”}

    编码 := xml.NewEncoder(os.Stdout)
    enc.Indent(" ", " ")
    if err := enc.Encode(v); 错误!=无{
        fmt.Printf("错误: %v\n", err)
    }

}

我可以理解struct Person,它有一个名为 varId的类型int,但是这些东西呢?

xml:"person" 
在 int 之后?这是什么意思?谢谢。

4

2 回答 2

6

这是一个结构标签。库使用这些来用额外信息注释结构字段;在这种情况下,模块encoding/xml使用这些结构标签来表示哪些标签对应于结构字段。

于 2013-09-08T21:47:02.047 回答
1

这意味着该变量将以 Person 示例的名称出现

type sample struct {
     dateofbirth string `xml:"dob"`
}

In the above example, the field 'dateofbirth' will present in the name of 'dob' in the XML.

你会在 go struct 中经常看到这个符号。

于 2018-09-07T07:09:29.573 回答