Go for Human Eyes
Order of Go Code
Go compiler reads an entire package at once, so order is not required for correctness. However, a consistent order is much easier for humans to scan and maintain.
Common top-to-bottom layout:
| Order | Section | What goes there |
|---|---|---|
| 1 | package | package main (file's package name) |
| 2 | import | Imported packages like fmt, math, etc. |
| 3 | type | Structs, interfaces, and other type definitions |
| 4 | func main() | Entry point for executable packages |
| 5 | Other functions and methods | Supporting helpers like WithTax() |
Why this order helps
Why is func main() listed above other functions and methods?
Think of it like an executive summary at the top of a report. It gives the big picture before you dive into details.
Why are import and type definitions at the top?
Think of it as setting the stage for an orchestra. It shows the instruments and their types before the music starts. These sections are the foundation for everything that follows.
System analogy
| Code type | Kitchen item | Why |
|---|---|---|
struct | The jar | Holds the data |
method / func | The appliance | Function that operates on the jar's contents, struct |
func { logic } | The recipe | Step-by-step instructions inside |
main | The chef | The master |
Where the Recipe Lives
In Go, the "recipe" is everything written between the { and the }.
func (p Product) WithTax() float64 {
// --- THIS IS THE RECIPE ---
taxRate := 1.10
result := p.Price * taxRate
return result
// --------------------------
}
More on the "Recipe"
The recipe is the logic inside the curly braces. It tells the chef (or the appliance) how to turn inputs into a result.
Where the recipe lives
In Go, the "recipe" is everything written between the { and the }.
func (p Product) WithTax() float64 {
// --- THIS IS THE RECIPE ---
taxRate := 1.10
result := p.Price * taxRate
return result
// --------------------------
}
Breaking down the recipe roles
| Part of the code | Recipe component | What it represents |
|---|---|---|
taxRate := 1.10 | The measurement | Defining a specific ratio or amount to use |
p.Price * taxRate | The action | The actual mixing, stirring, or math being done |
return result | The serving | Handing the finished dish back to the caller |
Two types of recipes in Go
Just like in a kitchen, you have different kinds of instructions.
1. The "chef's" recipe (method)
This is a recipe written specifically for one type of container (the jar).
Example: "How to bake this specific bread dough."
In Go: func (p Product) WithTax() — this recipe only works if you have a Product jar in your hand.
2. The "universal" recipe (standalone function)
This is a recipe that can be used on any ingredient, regardless of the jar it came from.
Example: "How to boil water." (It does not matter if the water came from a fancy bottle or the tap.)
In Go: func Add(a, b float64) — this recipe works on any two numbers you give it.