Skip to content

Chapter 03: Structures & Models ​

1 The Struct (The Container) ​

In Java or Python, you might use a Class. In Go, we use a struct. A struct is purely data. It has no hidden machinery.

go
type Book struct {
    ID      string  `json:"id"`
    Title   string  `json:"title"`
    Price   float64 `json:"price"`
}

Anatomy of the Code ​

  1. type: New Type Definition. We are inventing a custom data type named Book.
  2. struct: The kind of type. It means "Structure", a composite of fields.
  3. ID string: Field Name (ID) and Data Type (string).
    • Note: Capitalized ID means Public (Exported). If we wrote id (lowercase), other packages could not see it.
  4. `json:"id"`: The Tag. (See 8.2).

Comparison: Struct vs Class ​

FeatureJava ClassPython DataClassGo Struct
InheritanceYes (extends)YesNo (Composition)
MethodsInside ClassInside ClassAttached Separately
Visibilitypublic/private_ conventionCapitalized (Public)

2 Structs vs Pointers (The Blueprint vs The House) ​

Concept: Values and pointers. Both are copied when assigned or passed to a function. A copied pointer can still point to the same object. Signal: A Photocopy vs The Shared Document.

A struct copy is shallow: fields containing slices, maps, or pointers may still refer to shared data. Mutating that data differs from replacing the copied field. The float64 price above reflects the legacy API; the new book uses integer minor units plus currency and checks arithmetic bounds.

3 Tags (Reflecting Instructions) ​

What is that stuff in backticks? `json:"id"`?

This is Metadata. Imagine you are handing this struct to a specialized robot called the "JSON Encoder". The robot reads the tag:

"Oh, the human called this field ID in Go, but when I turn it into text for the browser, I should label it id (lowercase)."

If you omit tags, the JSON output will look like {"ID": "123"}, which is valid JSON. Choose field names as part of the API contract; JSON itself does not require a naming convention.

🎓 Knowledge Check: What is the difference between ID and id in a struct field?

Answer:

  • ID (Capitalized): Public (Exported). Visible to other packages and JSON encoders.
  • id (Lowercase): Private (Unexported). Hidden from everyone outside this package.

Released under the MIT License.