5

Take a look at this snip found at here

import (
    "encoding/xml"
    "fmt"
    "os"
)

func main() {
    type Address struct {
        City, State string
    }
    type Person struct {
        XMLName   xml.Name `xml:"person"`
        Id        int      `xml:"id,attr"`
        FirstName string   `xml:"name>first"`
        LastName  string   `xml:"name>last"`
        Age       int      `xml:"age"`
        Height    float32  `xml:"height,omitempty"`
        Married   bool
        Address
        Comment string `xml:",comment"`
    }

    v := &Person{Id: 13, FirstName: "John", LastName: "Doe", Age: 42}
    v.Comment = " Need more details. "
    v.Address = Address{"Hanga Roa", "Easter Island"}

    enc := xml.NewEncoder(os.Stdout)
    enc.Indent("  ", "    ")
    if err := enc.Encode(v); err != nil {
        fmt.Printf("error: %v\n", err)
    }

}

I can understand in the struct Person, It has a var called Id, which is of type int, but what about the stuff

xml:"person" 
after int? What does it mean? Thanks.

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 構造体でよく見られます。

于 2018-09-07T07:09:29.573 に答える