Go Basics
Hello World
package main
import "fmt"
func main() {
fmt.Println("Hello, world!")
}
Every Go program starts in package main. Execution begins in func main().
Packages
Every Go program is made of packages. By convention, the package name matches the last element of the import path — math/rand contains files that begin with package rand.
import (
"fmt"
"math/rand"
)
func main() {
fmt.Println("My favorite number is", rand.Intn(10))
}
Imports
Use the factored import statement (preferred style):
import (
"fmt"
"math"
)
Single import is also valid: import "fmt"
Exported Names
A name is exported if it begins with a capital letter.
Pizza,Pi→ exported ✅pizza,pi→ unexported ❌
When importing a package you can only use its exported names.
fmt.Println(math.Pi) // ✅
fmt.Println(math.pi) // ❌ compile error: undefined
Comments
// Single-line comment
/*
Multi-line comment
*/
Dependency Tracking
External packages are tracked via go.mod:
go mod init <module-path> # creates go.mod
go.sum contains cryptographic hashes of all direct + indirect dependencies for integrity verification:
rsc.io/quote v1.5.2 h1:w5fcysjrx7yqtD/aO+QwRjYZOKnaM9Uh2b40tElTs3Y=
rsc.io/quote v1.5.2/go.mod h1:LzX7hefJvL54yjefDEDHNONDjII0t9xZLPXsUe+TKr0=
Each line: <module-path> <version> <hash> (hash = algo:base64)
go mod tidy # add missing hashes, remove unused ones
External packages are found at pkg.go.dev.
Compilation
Go is compiled. Two kinds of errors:
| Kind | When | Impact |
|---|---|---|
| Compilation error | At build time | Binary not created — can't ship broken code |
| Runtime error | During execution | Can crash or misbehave in production |
String Formatting
| Function | Use |
|---|---|
fmt.Printf(...) | Print formatted string to stdout |
fmt.Sprintf(...) | Return formatted string |
fmt.Println(...) | Print with newline |
Format Verbs
| Verb | Type | Example output |
|---|---|---|
%v | Any (default) | 42, true, hello |
%T | Type name | int, string |
%s | String | hello |
%d | Integer | 42 |
%f | Float | 10.523000 |
%.2f | Float (2 dp) | 10.52 |
%q | Quoted string | "hello" |
%b | Binary | 101010 |
s := fmt.Sprintf("I am %d years old and %.2f meters tall", 25, 1.75)
// "I am 25 years old and 1.75 meters tall"