liveBook · Manning

Package

As explained in Go by Example

A Go package is a collection of Go source files that provides a namespace and compilation unit.

A Go package groups Go source files into a named namespace and compilation unit. Every Go program belongs to a package; an executable commonly uses package main with a main function. section 1.3

A minimal executable package

package main import "fmt" func main() { message := "Hello Gophers 👋!" fmt.Println(message) } Initialize a module and run the package with `go mod init github.com/username/repository` followed by `go run .`. section 1.3

Packages become especially useful when an application has distinct responsibilities. A link-shortening service can keep core link-management logic in link and expose HTTP handlers from link/rest. Handlers call the core service rather than duplicating its behavior. section 8.1

Design packages around clarity and genuine boundaries:

  • Start with a small, cohesive package when one is sufficient. section 8.8.1
  • Split into multiple packages when the application or team grows across domain boundaries. section 8.8.1
  • Choose descriptive package and item names that are clear, maintainable, easy to type, and easy to remember. section 8.1
  • Reuse standard-library packages for common capabilities such as string manipulation, HTTP servers, command-line flags, and testing. section 1.6
// gobyexample/hello.go
package main  #1

import "fmt"  #2

func main() {
    message := "Hello Gophers 👋!"  #3
    fmt.Println(message)
}

Inspect the complete package main example, including its import and entry point. section 1.3

Figure 8.1 The Shorten and Resolve handlers provide a REST API over HTTP using the Shortener service, which is backed by an in-memory database.
A screenshot of a computer

Description automatically generated

View how separate packages divide HTTP handlers from the in-memory link-shortening service. section 8.1

How Go by Example covers it

How deep it goes
Defines packages through runnable programs and service boundaries, then stops short of detailed compilation mechanics.
Examples
Uses a hello-world executable, a link-shortening REST service, and a standard-library HTTP server.
What you can do after
Build it from scratch by declaring, running, organizing, and naming Go packages for programs and services.
How it connects
Connects packages with modules, imports, HTTP handlers, standard library, interfaces, naming, and import cycles.

Also explained in

Compare how 7 books explain package →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go by Example. The section links point to the parts of the book it draws on.