Jiew Meng
Jiew Meng

Reputation: 88189

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

Upvotes: 5

Views: 1706

Answers (1)

Gujarat Santana
Gujarat Santana

Reputation: 10544

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

Upvotes: 5

Related Questions