Go (Golang) Cheatsheet
Setup & Environment
brew install go
# Download latest Go (replace version as needed)
wget https://go.dev/dl/go1.22.2.linux-amd64.tar.gz
sudo tar -C /usr/local -xzf go1.22.2.linux-amd64.tar.gz
# Add to PATH (add to ~/.bashrc or ~/.zshrc)
export PATH=$PATH:/usr/local/go/bin
- Download the MSI installer from https://go.dev/dl/
- Run the installer and follow the prompts
- Add Go to your PATH if not set automatically (usually
C:\Go\bin
)
go version
- Set up Go environment variables (add to ~/.bashrc or ~/.zshrc)
export GOPATH="$HOME/go"
export PATH="$PATH:$GOPATH/bin"
- Create a new Go module/project
mkdir myproject && cd myproject
go mod init github.com/username/myproject
Building & Running
go run main.go
go build -o myapp main.go
- Install binary to $GOPATH/bin
go install
go clean
Modules & Dependencies
go get github.com/sirupsen/logrus@latest
go list -m all
- Tidy up go.mod and go.sum
go mod tidy
go mod vendor
Testing
go test ./...
- Run tests with verbose output
go test -v ./...
- Run tests and show code coverage
go test -cover ./...
go test -bench .
Formatting & Linting
go fmt ./...
- Vet code (find suspicious constructs)
go vet ./...
- Lint code (requires golangci-lint)
golangci-lint run
Common Go Commands
- Download all dependencies
go mod download
go tool
- Show documentation for a package
go doc fmt
- Run a Go REPL (requires gore)
gore
Go File Structure
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
Common Code Patterns
var x int = 10
x := 10 // short form
const Pi = 3.14
func add(a int, b int) int {
return a + b
}
type User struct {
Name string
Age int
}
m := make(map[string]int)
m["foo"] = 42
s := []int{1, 2, 3}
s = append(s, 4)
for i := 0; i < 10; i++ {
fmt.Println(i)
}
if x > 0 {
fmt.Println("positive")
} else {
fmt.Println("non-positive")
}
switch day := 3; day {
case 1:
fmt.Println("Monday")
case 2:
fmt.Println("Tuesday")
default:
fmt.Println("Other day")
}
val, err := strconv.Atoi("123")
if err != nil {
log.Fatal(err)
}
go func() {
fmt.Println("Hello from goroutine")
}()
ch := make(chan int)
go func() { ch <- 42 }()
val := <-ch
Working with JSON, Files, and Type Conversion
Encoding and Decoding JSON
import (
"encoding/json"
"fmt"
)
type User struct {
Name string `json:"name"`
Age int `json:"age"`
}
user := User{Name: "Alice", Age: 30}
data, err := json.Marshal(user)
if err != nil {
fmt.Println("error:", err)
}
fmt.Println(string(data)) // {"name":"Alice","age":30}
var user User
jsonStr := `{"name":"Bob","age":25}`
err := json.Unmarshal([]byte(jsonStr), &user)
if err != nil {
fmt.Println("error:", err)
}
fmt.Printf("%+v\n", user) // {Name:Bob Age:25}
Opening, Reading, and Closing Files
- Read entire file into string
import (
"io/ioutil"
"fmt"
)
content, err := ioutil.ReadFile("file.txt")
if err != nil {
fmt.Println("error:", err)
}
fmt.Println(string(content))
- Open file, read line by line, and close
import (
"bufio"
"fmt"
"os"
)
file, err := os.Open("file.txt")
if err != nil {
fmt.Println("error:", err)
return
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
if err := scanner.Err(); err != nil {
fmt.Println("error:", err)
}
String and Integer Conversion
import (
"strconv"
"fmt"
)
s := "123"
i, err := strconv.Atoi(s)
if err != nil {
fmt.Println("error:", err)
}
fmt.Println(i) // 123
n := 456
s := strconv.Itoa(n)
fmt.Println(s) // "456"
Useful Packages
- "fmt" — formatted I/O
- "os" — OS functions
- "io/ioutil" — file I/O
- "net/http" — HTTP client/server
- "encoding/json" — JSON encoding/decoding
- "time" — time and date
- "log" — logging
- "context" — context for cancellation/timeouts
Go Modules Example (go.mod)
module github.com/username/myproject
go 1.22
require (
github.com/sirupsen/logrus v1.9.0
)
Resources