5

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?
Jiew Meng
  • 84,767
  • 185
  • 495
  • 805

1 Answers1

5

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

Sameer Azazi
  • 1,503
  • 10
  • 16
Gujarat Santana
  • 9,854
  • 17
  • 53
  • 75
  • 3
    There is a little inaccuracy in the last line of your answer. Non declared fields will have `zero value` (`nil` & `zero value` are not same). https://tour.golang.org/basics/12 – Sameer Azazi Feb 26 '17 at 15:02
  • @SameerAzazi Thanks for pointing out. please edit if you found some inaccuracy in the answer. – Gujarat Santana Feb 26 '17 at 15:04
  • @GujaratSantana, Thank you for your answer. But I still dont understand the "* How does the OmitID part prevent id from being set?*" part. It seems like if I pass an `id`, it will override the `id` field? How does having OmitID prevent this from happening? – Jiew Meng Feb 27 '17 at 09:22
  • It is because of `tags` json at line `193` in the code. there is omitempty. – Gujarat Santana Feb 27 '17 at 09:56
  • @JiewMeng you can read more here https://golang.org/pkg/encoding/json/#Marshal. `The "omitempty" option specifies that the field should be omitted from the encoding if the field has an empty value, defined as false, 0, a nil pointer, a nil interface value, and any empty array, slice, map, or string.` – Gujarat Santana Feb 27 '17 at 09:57