# Go Cheatsheet
2 min read
Table of Contents
This cheatsheet gives you a quick reference to Go’s syntax, tools, and best practices. Keep it handy while coding.
Basics
Hello World:
package main
import "fmt"
func main() { fmt.Println("Hello, World!")}Variables:
var name string = "Alice"age := 30 // shorthand, type inferredConstants:
const Pi = 3.14Functions:
func add(a int, b int) int { return a + b}Data Types
string,int,float64,bool- Arrays:
[3]int{1, 2, 3} - Slices:
[]int{1, 2, 3} - Maps:
map[string]int{"Alice": 30} - Structs:
type Person struct { Name string Age int}Control Structures
If/Else:
if x > 0 { fmt.Println("Positive")} else { fmt.Println("Non-positive")}Switch:
switch day {case "Monday": fmt.Println("Start of week")default: fmt.Println("Other day")}For loops:
for i := 0; i < 5; i++ { fmt.Println(i)}Pointers
x := 10p := &xfmt.Println(*p) // dereferenceConcurrency
Goroutines:
go func() { fmt.Println("Hello from a goroutine")}()Channels:
ch := make(chan int)go func() { ch <- 42 }()fmt.Println(<-ch)Error Handling
data, err := os.ReadFile("file.txt")if err != nil { log.Fatal(err)}Testing
Create example_test.go:
package main
import "testing"
func TestAdd(t *testing.T) { if add(2, 3) != 5 { t.Error("Expected 5") }}Run tests:
go testTooling Commands
go run file.go— Run a programgo build— Compile to binarygo test— Run testsgo fmt— Format codego get— Fetch dependenciesgo mod init <module>— Create a module
Best Practices
- Keep functions short and focused
- Use
gofmtto ensure consistent style - Handle errors explicitly
- Prefer composition over inheritance
- Keep your
mainpackage minimal
Final Thoughts
Go’s simplicity makes it easy to remember the basics, but this cheatsheet is a great quick refresher when you need it.