Hello World in Go
Every Go program, from tally to Kubernetes, starts the same way. Once you can read the smallest program line by line, every other Go file looks familiar.
The rule
package mainplusfunc mainmakes a program; import only what you use.
Save this as main.go inside the tally module:
package main
import "fmt"
func main() {
fmt.Println("tally is ready")
}Run it with go run . and it prints tally is ready.
package main: every Go file starts by naming its package. The special namemainsays "this builds an executable", not a library.import "fmt": brings in the standard formatting package. Several imports go in a parenthesised block, one per line:import ( "fmt" "os" )written over four lines.func main(): the entry point. It takes no arguments and returns nothing. Whenmainreturns, the program ends. Command-line arguments come fromos.Argsinstead.fmt.Println: you call something from a package aspackage.Name. It starts with a capital letter because only capitalised names are visible outside their package.
Go is strict in a helpful way:
- An unused import is a compile error, not a warning. So is an unused local variable.
- The opening brace
{must sit on the same line asfunc main(). Go inserts semicolons at line ends automatically, so a brace on the next line breaks the statement. - Indentation uses tabs, and
go fmtfixes layout for you.
Notice what is missing, too: no class wrapping main, no semicolons at line ends, no return 0. A program that exits normally reports success to the operating system; to signal failure you call os.Exit(1), which tally will do when it cannot open a file.
The shortcut
Read any Go file top-down with three checkpoints: package, imports, main.
Package
The first line says
package main, so this can become a program.
The same checkpoints catch the second classic error: a file in package tally with a func main builds only as a library, and go run refuses it, because only package main produces a program.
Drills
Answer fast — trust the rule.
Which package name makes a Go file part of an executable program?
A file imports "strings" but never uses it. What happens?
Why is it fmt.Println and not fmt.println?
How does main get the command-line arguments in tally notes.txt?
Remember
package mainplusfunc mainmakes a program; import only what you use.- Shortcut: check package, imports, main — in that order.
- Trap: unused imports and a
{on the next line both stop the build.
