英文:
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:"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)
}
}
</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:"person"
</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:"dob"`
}
In the above example, the field 'dateofbirth' will present in the name of 'dob' in the XML.
you will see this notation often in go struct.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论