1. Packages and namespaces
When you write your first programs, a single file like main.go looks perfectly fine. But after a couple of days, you have ten functions, a couple of constants, several variables, and suddenly the file starts to feel like a closet where you “just for a minute” put some things, then “just for a minute” put in some more, and now you are already living inside the closet.
A package in Go solves exactly this problem: it lets you group code by meaning and gives you rules for who can “see” and use what. As a result, your project starts to look like a tidy kitchen with drawers, not like a pot where there are spoons, socks, and the mystery of “why does it work”.
Package as a namespace: “the name before the dot” is not magic
If you have already written fmt.Println("hello"), then you have seen the most important symptom of packages existing: the dot.
fmt.Println is read like this: “in the fmt package, take the exported name Println.” In other words, a package is literally a namespace that protects you from the situation where a program has 15 functions called Print() and you do not understand which one is “the one”.
It can be imagined like this:
- a package is a surname,
- a function/type/variable is a first name,
- and fmt.Println is “Ivan Petrov”, only for code.
And what is nice: in Go this is not a convention, but a real language mechanism.
The package line ...: how a file belongs to a package
Any .go file (except for special cases we are not touching today) starts with a package line — package <name>.
It is important to get the idea: a file by itself is not a “unit of a program”. The unit is the package, and a file is just one piece of the package.
Here is a minimal example:
package main
import "fmt"
func main() {
fmt.Println("hi") // hi
}
The package main line means: “this file belongs to the main package.”
Now here is a key practical fact that saves hours of life: all files with the same package in one folder are treated as one package. That means they share a common scope at the package level.
Package-level scope: visibility inside a package
Now comes an important point: inside one package, all files can see each other’s declarations. Not “if you import”, not “if you connect”, but simply see them, because they are one package.
Let us continue our educational mini-program. Let it be the simplest “day balance”: we read income and expense, calculate the difference, and print a report. Earlier you would have written everything in main.go. Today we will start splitting the code into files, but for now we will keep one package: main.
File main.go
In this file we will have the “scenario”: read, calculate, output.
package main
import "fmt"
func main() {
income, expense := readIncomeExpense()
balance := income - expense
fmt.Println(formatReport(income, expense, balance))
}
Pay attention: readIncomeExpense and formatReport are not declared here. And that is fine — they can live in other files of the same package.
File io.go
Now we make input reading a separate function, in a separate file, but in the same package:
package main
import "fmt"
func readIncomeExpense() (int, int) {
var income int
var expense int
fmt.Scan(&income, &expense)
return income, expense
}
File report.go
And we will move report formatting out as well:
package main
import "fmt"
func formatReport(income, expense, balance int) string {
return fmt.Sprintf("income=%d expense=%d balance=%d", income, expense, balance)
}
The key point is that all three files are parts of one package main, so they can call each other’s functions without any issue. This is what package-level scope is: scope at the package level.
To help this fit in your head, here is a diagram:
flowchart TD
A[Project folder] --> B[main.go package main]
A --> C[io.go package main]
A --> D[report.go package main]
B --> E[One package: main]
C --> E
D --> E
E --> F[Shared names at package level: readIncomeExpense, formatReport, ...]
If you caught yourself thinking “so the file is not the boundary?”, then yes: the boundary is the package, not the file. And that is very Go-like: fewer entities, less confusion.
2. package main and the entry point
Usually a package is just a container for code. But main is a special case: the program starts from the main package, and the entry point is the main() function.
You can say it like this: if a package is a “box of parts”, then package main is the box from which an executable program is assembled, not a library.
Another useful fact: when Go analyzes a program, it looks at entry points for each main package — among them are the main function and also package initialization mechanisms.
We will deal with initialization separately, and today it is enough to keep this idea in mind: main is the “entry into the application”, and it usually contains the glue for the scenario.
3. Export: public and internal API
Exported and unexported names: the first-letter rule
Now — the central topic of the lecture, the reason we set all this up.
In Go there is a very simple rule:
- a name starts with a capital letter → it is exported and available from other packages;
- a name starts with a lowercase letter → it is unexported and available only inside its own package.
And this applies to functions, variables, constants, types, and later also methods and struct fields.
Example from the standard library: fmt.Println vs “what if fmt.println?”
Let us “feel” this rule directly:
package main
import "fmt"
func main() {
fmt.Println("ok") // ok
// fmt.println("no") // compilation error: there is no such exported name
}
Why does Println with a capital letter exist, while println with a lowercase letter does not? Because the fmt package exports Println, meaning it makes it part of the public API.
A little table so the brain does not pretend it “already got it”
| Name | Example | Available from another package? | Why |
|---|---|---|---|
| Exported | |
Yes | The first letter is uppercase |
| Unexported | |
No | The first letter is lowercase |
Yes, it looks too simple to be true. But that is really how it works. And this is one of the reasons people like Go: fewer rules, fewer surprises.
Export: inside a package and outside it
It is easy to get confused now: “if I have formatReport with a lowercase letter, does that mean main.go cannot call it?” It can, because main.go and report.go are in the same package.
Export/unexport affects only access between packages. Inside one package, both exported and unexported names are available.
Let us improve our code and make formatReport an internal detail, while a more “human-friendly” function sticks out to the outside world in the future. While we are in one package, there will be no difference in access, but the meaning will be there.
File report.go (version with an internal function)
package main
import "fmt"
func formatReport(income, expense, balance int) string {
return fmt.Sprintf("income=%d expense=%d balance=%d", income, expense, balance)
}
This is an unexported function — an “internal helper”.
File main.go (uses the internal function)
package main
import "fmt"
func main() {
income, expense := readIncomeExpense()
balance := income - expense
fmt.Println(formatReport(income, expense, balance))
}
It works because the package is one.
But if we tried to call formatReport from another package, it would not be available. That is exactly the meaning of a lowercase letter: “do not touch this, it is internal.”
Export is a contract, not “secrecy”
It is very tempting to think that “unexported” is something about security. In reality, no: it is first and foremost about a contract and promises.
When you export a name, you are as if telling the outside world: “You can use this. I will try not to break it without reason.” Therefore the public API of a package is a set of exported identifiers: constants, types, variables, functions, and also (when we get to structs) exported fields and methods.
This leads to a very practical design rule even for beginners: do not export everything. If you make every tiny helper function public, you will turn your package into a Saturday market: everything seems to be there, but it is impossible to find what you need, and the sellers (that is, you a week later) do not even remember where anything is.
To feel the idea, imagine that you are making a “balance calculator” package (in the future we will learn how to organize such things as separate packages). A public contract is a good place for things like ComputeBalance(...), while parseIncomeFromWeirdLegacyFormat(...) is better left internal: it is needed, but it should not be an “obligation” for outside code.
4. Naming rules and a small refactoring
Naming rules: how to name things
Names in Go are not just “beauty”. Because of packages and export, names become part of the architecture. And if a name is chosen badly, not only your eyes start to hurt, but also imports, code reading, and everything else.
Let us start with the most common beginner trap: naming variables after packages. This is especially annoying because the error looks like “it worked yesterday, today it does not”, while the reason is just one line.
Example: how to accidentally “break fmt”
package main
import "fmt"
func main() {
fmt.Println("before") // before
fmt := "oops"
_ = fmt
// fmt.Println("after") // error: fmt is now a variable, not a package
}
Inside main you created a variable named fmt, and it “shadowed” the fmt package in this scope. Yes, the compiler honestly saves you and will not let you build the program, but it does not fix your mood.
The second important principle: exported names should be simple and predictable. If you make a name public, it becomes part of the API, which means people will read it. And people are delicate creatures: if it is inconvenient, they go to another package.
Mini table: “more readable” vs “less readable”
| Intention | Better | Worse | Why |
|---|---|---|---|
| Public function | |
|
In Go, it is not customary to shout in all caps |
| Internal helper | |
|
_ is rarely used in names |
| Local variable | |
|
i is fine in a loop, but not for meaning |
Readability is highly valued in Go, and packages strengthen this value: a name is visible not only in the file, but also “through the dot” in other places.
Micro-practice: hide details and make an API
To reinforce “export = contract”, let us do a small refactoring in our mini application. We will add a function that will be the “main” one for the report, and we will hide the internal details behind lowercase letters.
File report.go (public + internal)
package main
import "fmt"
func PrintBalanceReport(income, expense int) string {
balance := income - expense
return formatReport(income, expense, balance)
}
func formatReport(income, expense, balance int) string {
return fmt.Sprintf("income=%d expense=%d balance=%d", income, expense, balance)
}
We are still in the main package, so this is more of a “think about it” exercise. But it is important: you begin to build an API even inside one package so that later it is easier to extract code into separate packages when the time comes.
File main.go (using the public function)
package main
import "fmt"
func main() {
income, expense := readIncomeExpense()
fmt.Println(PrintBalanceReport(income, expense)) // income=... expense=... balance=...
}
From the code’s point of view, reading becomes nicer: main now knows less about the report details.
5. Typical mistakes
Mistake #1: thinking that “export” affects access between files in the same package.
This is a common confusion after languages where the file is an important boundary. In Go the boundary is the package. If two files are declared as package main and are in the same folder, they are in one package and can see each other at the level of package-level declarations. Export controls access between packages, not between files.
Mistake #2: trying to call fmt.println or “guessing” a name in a package.
A beginner sometimes reasons like this: “Well, Println prints, so println should print too.” It should not. In Go, access to names from another package is determined by export: if a name is not exported, you will not see it. The right reaction is to open the package documentation or IDE hints, not guess “what it is called there”.
Mistake #3: exporting everything just in case.
When you use a capital letter, you are, in essence, publicly promising support for that name. In large projects, a public API is a serious responsibility: it is harder to change, and it needs to be maintained. So it is better to get used from the start to exporting only what is really a clear entry point, and leaving everything auxiliary inside the package. The idea that public APIs consist of exported package identifiers is fundamental in Go.
Mistake #4: “breaking” a package with a variable of the same name (for example, fmt := ...).
This looks like a small thing, but it breaks reading and causes very annoying compilation errors. If you imported a package, do not use its name for variables. If your hand wants to type fmt := ..., it is better to stop and choose a name by meaning: msg, line, text, report.
Mistake #5: confusing the meaning of package main with ordinary packages.
Sometimes there is a temptation to write “package main everywhere, so it works”. Of course, it will work... for a while. But main is the application package, the entry point, the place for “gluing things together”. In real code, you almost always want most of the logic to live not in main, but in other packages, while main only assembles everything. While we are learning with small examples, main is fine, but it is important not to turn it into a “dumping ground”.
GO TO FULL VERSION