Go String after variable declaration

huangapple go评论95阅读模式
英文:

Go String after variable declaration

问题

请看这个在这里找到的代码片段:

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)
	}

}

我可以理解在struct Person中,它有一个名为Id的变量,类型为int,但是在int之后的xml:"person"是什么意思呢?谢谢。

英文:

Take a look at this snip found at here

<pre>
import (
"encoding/xml"
"fmt"
"os"
)

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

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

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

}

</pre>

I can understand in the struct Person, It has a var called Id, which is of type int, but what about the stuff <pre>xml:&quot;person&quot; </pre>after int? What does it mean? Thanks.

答案1

得分: 5

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

英文:

It's a struct tag. Libraries use these to annotate struct fields with extra information; in this case, the module encoding/xml uses these struct tags to denote which tags correspond to the struct fields.

答案2

得分: 0

这意味着变量将出现在Person名称中的含义示例

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

在上面的示例中,字段'dateofbirth'将在XML中以'dob'的名称出现。

你会经常在Go结构体中看到这种表示法。

英文:

which mean that variable will present in the name of Person example

type sample struct {
     dateofbirth string `xml:&quot;dob&quot;`
}

In the above example, the field &#39;dateofbirth&#39; will present in the name of &#39;dob&#39; in the XML.

you will see this notation often in go struct.

huangapple
  • 本文由 发表于 2013年9月9日 04:56:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/18688578.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定