Every Go program follows a clear and consistent structure with these main components:
main() function for executable programsLet's write the classic "Hello, World!" program to understand these components:
// File: main.go
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
Package Declaration (package main)
main package is special - it tells Go this is an executable programImport Statement (import "fmt")
fmt provides functions for formatted I/O operationsMain Function (func main())
main packageNo Semicolons
for loops)Code Formatting
go fmt to automatically format your codeSave the Code
main.goRun the Program
# Run directly
$ go run main.go
Hello, World!
# Or build and run
$ go build main.go
$ ./main
Hello, World!
Understanding Build Commands
go run: Compiles and runs in one step (good for development)go build: Creates an executable (good for deployment)File Organization
Code Style
go fmt before committing code