What is a "package" in golang? Official explanation/glossary

I would like to understand what “package” means in the context of golang.

The Go Programming Language Specification has a section about it, but I am new to golang and
looking for something glossary-like explanation of the term “package”.

1 Like

Edit, sorry, I provided my own answer rather than a pointer to an official one. Probably not official, but here’s a brief description from the Donovan and Kernighan book, page 2 https://www.gopl.io/ch1.pdf

Go code is organized into packages, which are similar to libraries or modules in other languages. A package consists of one or more .go source files in a single directory that define what the package does. Each source file begins with a package declaration, here package main, that states which package the file belongs to…

1 Like

@mje thank you for your answer.

Here are two rule which I reverse-engineered by reading the errors which I get from vscode:

package rule 1:

Imagine you have two files: mydir/a.go and mydir/b.go

If a.go uses “package main”, then b.go must use “package main”, too.

package rule 2:

if a.go defines a function, then b.go can use the function without importing it.

Are these rules correct? Are there official docs about this (for users, no the language spec)?

I am currently learning golang via the tutorial and gobyexample. AFAIK both sources don’t explain
above rules. But maybe I missed it.

The Go language specification has a lot of text about packages, though in a “spec” manor and therefore not necessarily easy to read:

Pardon me citing a book, and I suppose this reveals my age, but I learned Go from the Donovan & Kernighan (as I learned C from K&R and Java from Gosling), so I don’t know online references as thoroughly.

Rule 1:
The Donovan & Kernighan section 2.6. It also mentions that the organization of packages in files and directories is a property of the go tool rather than specified in the language spec. It goes on to describe that in detail in chapter 10. Note that the book predates go modules.

Rule 2:
Paragraph three in 2.6.

Some other rules to keep in mind

Rule #3
to export a symbol (variable, constant, func, struct, interface) from a package (make it visible from another package), its name shall start with capital letter

package foo

var foo int // not exported

const Bar  = "hello world" // exported

func MyFunc() error {. //exported
    return nil

Rule #4
All symbols declared in a package (exported or not) are always visible to all files inside the same package without need to import the package

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.