Your First Go Program
Prerequisites: Installing Go
Every Go project lives in a module — a folder with a go.mod
file that names the project and records its dependencies. Create
one:
mkdir hello
cd hello
go mod init example.com/hello
That generates go.mod:
module example.com/hello
go 1.23.4
The module path (example.com/hello) is just a unique name; it
only needs to be a real URL if you later publish the code.
Now create main.go in the same folder:
package main
import "fmt"
func main() {
fmt.Println("Hello, world!")
}
And run it:
go run .
Expected output
Hello, world!
Line by line:
package main— every Go file belongs to a package. The special packagemainproduces a runnable program (rather than a library).import "fmt"— brings in the standard library's formatting package, which handles printing.func main()— the program's entry point. It takes no arguments and returns nothing.fmt.Println(...)— prints its arguments followed by a newline. The capitalPmatters: in Go, names starting with an uppercase letter are exported (visible outside their package).
Common mistakes
- Putting the opening brace on its own line. Go inserts
semicolons automatically at line ends, so
func main()followed by{on the next line is a compile error. - Importing a package and not using it —
"fmt" imported and not usedis a compile error, not a warning.
Practice
Change the program to print your own name on one line and your favorite language on the next.
Show solution
package main
import "fmt"
func main() {
fmt.Println("Ada")
fmt.Println("Go")
}