liveBook · Manning

Entry point

As explained in Go in Action, Second Edition

The main function is the specially named Go function that serves as the starting point of an executable program.

An executable Go program starts at main() in package main. The package declaration tells the compiler to produce a standalone program; it then looks for main() among the files in that package. With both present, the result is an executable that can run from the command line. section 2.4.5

Keep each executable’s entry point in its own main package. A project with several tools or services can place them in separate subdirectories under cmd, such as cmd/myapp/main.go, while sharing code through other packages. section 11.1.1

Starting work is not the same as finishing it

An RSS reader can fetch a feed inside main(). Moving the fetch into a goroutine lets main() continue, but if main() returns immediately, the program exits before the feed title is printed. main() must remain active until background work finishes; a fixed sleep only guesses at the required time. section 9.1

Listing 9.3 main.go: Fetching data via a goroutine
package main

...

func main() {
 fp := gofeed.NewParser()
 go func(url string) { #1
  feed, _ := fp.ParseURL(url) #2
  fmt.Println(feed.Title)
 }("https://rss.nytimes.com/services/xml/rss/nyt/World.xml") #3

}

The asynchronous RSS-fetch listing shows main() launching a goroutine with no subsequent wait, exposing why the entry point also governs program lifetime. section 9.1

How Go in Action, Second Edition covers it

How deep it goes
Explains compiler discovery and program lifetime, but defers robust goroutine synchronization.
Examples
Uses an RSS-feed fetch, a prematurely exiting goroutine, and a cmd/myapp/main.go layout.
What it assumes
Introduces packages as Go’s basic organizational unit before identifying the executable entry point.
What you can do after
Build it from scratch as a Go executable with package main and main(), while accounting for background work before main() returns.
How it connects
Connects package organization, executable compilation, cmd directories, and goroutine lifetime.

Also explained in

Compare how 10 books explain entry point →

Related concepts

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