英文:
Golang struct {}{} meaning
问题
我正在查看chi包的文档。我看到了这样的内容:
https://github.com/pressly/chi/blob/master/_examples/rest/main.go#L154
data := struct {
*Article
OmitID interface{} `json:"id,omitempty"` // prevents 'id' from being overridden
}{Article: article}
我如何解释这段代码?有两个部分我不太理解:
OmitID
部分如何防止设置id
?{Article: article}
部分是什么作用?
英文:
I am looking at the docs for the chi package. I see something like:
https://github.com/pressly/chi/blob/master/_examples/rest/main.go#L154
data := struct {
*Article
OmitID interface{} `json:"id,omitempty"` // prevents 'id' from being overridden
}{Article: article}
How do I interpret this? 2 parts I don't fully understand
- How does the
OmitID
part preventid
from being set? - What does the
{Article: article}
part do?
答案1
得分: 5
在struct
定义中,第一个{}
用于定义该结构体的字段或属性。
data := struct {
*Article
OmitID interface{} `json:"id,omitempty"` // prevents 'id' from being overridden
}
所以data
是一个结构体,它有字段*Article
和OmitID
,并且它们各自有自己的类型。
{Article: article}
部分是做什么用的?
第二个{}
用于定义该字段的值。
{Article: article}
这部分定义了Article
字段的值。
OmitID
部分如何防止设置id
?
在Go语言中,你可以在结构体中定义任意数量的字段,并且可以通过调用字段和相应类型的值来定义它。例如,如果我有以下结构体:
type DriverData struct {
Name string `json:"name"`
Status bool `json:"status"`
Location GeoJson `json:"location"`
}
我可以这样调用它:
example := DriverData{Name: "SampleName"}
其余的字段将根据它们各自的数据类型具有零值
。
你可以在这里了解关于Go语言零值
的更多信息:链接
英文:
The first {}
in the struct
definition is for define the field or attribute of that struct.
data := struct {
*Article
OmitID interface{} `json:"id,omitempty"` // prevents 'id' from being overridden
}
So the data
is a struct that has fields *Article
and OmitID
with their respected type.
> What does the {Article: article} part do?
the second {}
is for defining the value of that field.
{Article: article}
this part is defining the value of Article
field.
> How does the OmitID part prevent id from being set?
In go you can define any number of field in the struct.
And you can call define it by calling the field and the value with the respected type. for example if I have this struct :
type DriverData struct {
Name string `json:"name"`
Status bool `json:"status"`
Location GeoJson `json:"location"`
}
I can call it like this :
example := DriverData{Name : "SampleName"}
the rest of the field will have zero values
based on their respective data types.
You can read about golang Zero Values
here
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论