简体   繁体   中英

Golang struct {}{} meaning

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM