Go by Example

Hello, World

The smallest runnable Go program - package main, the main function, and fmt.Println.

The smallest complete Go program proves the toolchain is wired up and your code runs. An executable is built from a package named main, which defines the main function that starts the program. A module can contain multiple executable packages in different directories; there are no global scripts or implicit execution.

Go source files are grouped into packages. A package named main can be built as an executable. fmt.Println writes its arguments to stdout followed by a newline.

package main
 
import "fmt"
 
func main() {
    fmt.Println("Hello, World!")
}

Run it directly with go run:

OUTPUT
$ go run hello.go
Hello, World!

Or compile it into a binary first:

OUTPUT
$ go build -o hello hello.go
$ ./hello
Hello, World!

Pure Go programs often run in minimal containers, but a build is not guaranteed to be statically linked. Programs that use cgo or depend on system data such as CA certificates may need libraries or files in the image.

In production

fmt.Println writes plain text to stdout. In a service, structured log fields such as severity and request ID make events easier to filter. Write logs to the stream your runtime collects, usually stdout or stderr, and keep command output separate from diagnostic logs.

Enjoyed this? Get more software craft delivered to your inbox.