Golang中的`struct {}{}`的含义是什么?

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

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 prevent id 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是一个结构体,它有字段*ArticleOmitID,并且它们各自有自己的类型。

{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

huangapple
  • 本文由 发表于 2017年2月26日 22:40:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/42469833.html
匿名

发表评论

匿名网友

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

确定