Go Quick Reference
Everything you need day‑to‑day – syntax, concurrency, and best practices.
Basic Syntax
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println("Hello, World!")
}
Variables & Constants
var name string = "Alice" var age int = 25 var isActive bool = true // Short declaration (inside functions) name := "Alice" age := 25 // Multiple variables var x, y int = 1, 2 a, b := "hello", true // Constants const Pi = 3.14159 const ( StatusOK = 200 StatusNotFound = 404 ) // Zero values var i int // 0 var s string // "" var b bool // false var p *int // nil
Data Types
Basic Types
boolstringint, int8, int16, int32, int64uint, uint8, uint16, uint32, uint64float32, float64complex64, complex128byte– alias for uint8rune– alias for int32 (Unicode)
Composite Types
array– fixed sizeslice– dynamic arraymap– key‑valuestruct– fieldsinterface– method setschannel– for concurrencypointer– *Tfunction– first‑class
Type Conversion
i := 42
f := float64(i)
u := uint(f)
s := "123"
n, err := strconv.Atoi(s) // string → int
Control Flow
if / else
if x > 0 { fmt.Println("positive") } else if x < 0 { fmt.Println("negative") } else { fmt.Println("zero") } // With initialization if err := doSomething(); err != nil { return err }
switch
// Expression switch switch day { case "Monday": fmt.Println("Start of week") case "Friday": fmt.Println("TGIF") default: fmt.Println("Other day") } // Condition switch (no expression) switch { case score >= 90: grade = "A" case score >= 80: grade = "B" default: grade = "C" } // Multiple cases switch x { case 1, 2, 3: fmt.Println("1-3") case 4, 5: fmt.Println("4-5") } // Fallthrough switch x { case 1: fmt.Println("one") fallthrough case 2: fmt.Println("two") }
for Loop
// Standard for for i := 0; i < 10; i++ { fmt.Println(i) } // While‑style for i < 10 { fmt.Println(i) i++ } // Infinite loop for { fmt.Println("running...") } // Range (slice/map/string/channel) nums := []int{1, 2, 3, 4} for idx, val := range nums { fmt.Println(idx, val) } // Range with index only for idx := range nums { fmt.Println(idx) } // Range over map for key, value := range myMap { fmt.Println(key, value) } // Range over string (runes) for pos, char := range "hello" { fmt.Println(pos, char) } // break / continue for i := 0; i < 10; i++ { if i%2 == 0 { continue } if i > 7 { break } fmt.Println(i) }
Functions
// Basic function func add(a int, b int) int { return a + b } // Multiple return values func divide(a, b int) (int, error) { if b == 0 { return 0, errors.New("division by zero") } return a / b, nil } // Named return values func split(sum int) (x, y int) { x = sum * 4 / 9 y = sum - x return // naked return } // Variadic function func sum(nums ...int) int { total := 0 for _, n := range nums { total += n } return total } // Defer (executed on return) func readFile() { f, err := os.Open("file.txt") defer f.Close() // runs after function returns // ... }
Pointers
x := 42 ptr := &x // pointer to x fmt.Println(*ptr) // 42 (dereference) *ptr = 21 // change x via pointer fmt.Println(x) // 21 // Function with pointer func increment(n *int) { *n = *n + 1 } increment(&x)
Structs
type Person struct { Name string Age int City string } // Create instances p1 := Person{"Alice", 25, "Delhi"} p2 := Person{Name: "Bob", Age: 30} p3 := new(Person) // zero‑valued pointer // Access fields fmt.Println(p1.Name) p1.Age = 26 // Struct methods (value receiver) func (p Person) Greet() string { return "Hello, " + p.Name } // Struct methods (pointer receiver – modifies) func (p *Person) Birthday() { p.Age++ } // Embedding type Employee struct { Person // embedded EmployeeID int Salary float64 } e := Employee{Person{"Alice", 25, "Delhi"}, 1234, 75000} fmt.Println(e.Name) // promoted from Person
Interfaces
type Greeter interface { Greet() string } // Types implement interfaces implicitly func (p Person) Greet() string { return "Hello, " + p.Name } // Use interface func sayHello(g Greeter) { fmt.Println(g.Greet()) } // Empty interface (any type) var anything interface{} anything = 42 anything = "string" anything = Person{} // Type assertion val, ok := anything.(int) if ok { fmt.Println("int:", val) } // Type switch switch v := anything.(type) { case int: fmt.Println("int:", v) case string: fmt.Println("string:", v) default: fmt.Println("unknown") }
Error Handling
// Errors are values import "errors" func divide(a, b float64) (float64, error) { if b == 0 { return 0, errors.New("division by zero") } return a / b, nil } // Check errors result, err := divide(10, 0) if err != nil { fmt.Println("Error:", err) return } fmt.Println(result) // Custom error type type MyError struct { Code int Msg string } func (e MyError) Error() string { return fmt.Sprintf("error %d: %s", e.Code, e.Msg) } // Panic and recover (rarely used) defer func() { if r := recover(); r != nil { fmt.Println("Recovered:", r) } }() panic("something went wrong")
Goroutines
// Start a goroutine go doSomething() // Example func printNumbers() { for i := 0; i < 5; i++ { time.Sleep(100 * time.Millisecond) fmt.Println(i) } } go printNumbers() // Anonymous goroutine go func() { fmt.Println("Running in goroutine") }()
Channels
// Create channel ch := make(chan int) // Buffered channel ch := make(chan int, 2) // Send and receive ch <- 42 // send value := <-ch // receive // Channel example func worker(ch chan int) { ch <- 42 } ch := make(chan int) go worker(ch) result := <-ch fmt.Println(result) // Close channel close(ch) // Range over channel for value := range ch { fmt.Println(value) } // Select select { case v := <-ch1: fmt.Println("ch1:", v) case v := <-ch2: fmt.Println("ch2:", v) case <-time.After(1 * time.Second): fmt.Println("timeout") default: fmt.Println("no activity") }
Slices
// Create slice s := []int{1, 2, 3, 4} // Append s = append(s, 5, 6) // Make slice s := make([]int, 5) // length 5, capacity 5 s := make([]int, 5, 10) // length 5, capacity 10 // Slice operations s = []int{1, 2, 3, 4, 5} sub := s[1:4] // [2, 3, 4] sub := s[:3] // [1, 2, 3] sub := s[2:] // [3, 4, 5] // Copy dst := make([]int, len(s)) copy(dst, s)
Maps
// Create map m := map[string]int{ "Alice": 25, "Bob": 30, } // Make map m := make(map[string]int) m["Alice"] = 25 m["Bob"] = 30 // Access age := m["Alice"] age, ok := m["Charlie"] // ok = false if not found // Delete delete(m, "Bob") // Iterate for key, value := range m { fmt.Println(key, value) } // Map length fmt.Println(len(m))
Packages & Imports
// Import import "fmt" import "math/rand" import "strings" // Multiple imports import ( "fmt" "math/rand" "strings" ) // Alias import r "math/rand" // Blank import (for init side‑effects) import _ "image/png"
Common Standard Library
fmt
fmt.Println(v)fmt.Printf("v: %v", v)fmt.Sprintf(format, v)fmt.Errorf("error: %v", err)
strconv
strconv.Atoi(s)– string → intstrconv.Itoa(i)– int → stringstrconv.ParseFloat(s, 64)strconv.FormatFloat(f, 'f', -1, 64)
strings
strings.Contains(s, substr)strings.Split(s, sep)strings.Join(slice, sep)strings.ReplaceAll(s, old, new)strings.ToUpper(s)strings.TrimSpace(s)
os
os.Open(name)os.Create(name)os.Stat(name)os.Getenv(key)os.Args– command‑line args
Testing
// file: math_test.go package math import "testing" func TestAdd(t *testing.T) { result := add(2, 3) expected := 5 if result != expected { t.Errorf("add(2, 3) = %d; want %d", result, expected) } } func TestAddTable(t *testing.T) { tests := []struct{ a, b, expected int }{ {1, 1, 2}, {2, 3, 5}, {10, 20, 30}, } for _, test := range tests { result := add(test.a, test.b) if result != test.expected { t.Errorf("add(%d, %d) = %d; want %d", test.a, test.b, result, test.expected) } } }
Best Practices
- Use
go fmtto format code automatically. - Use
go vetto detect suspicious constructs. - Use
golangci-lintfor comprehensive linting. - Handle errors – never ignore them.
- Use
context.Contextfor cancellation and timeouts. - Use
sync.WaitGroupto wait for goroutines. - Avoid global state – pass dependencies explicitly.
- Use
io.Readerandio.Writerfor streaming data. - Write tests – aim for good coverage.
- Use meaningful package names – short, lowercase.
- Follow the
Goproject structure –cmd/,pkg/,internal/. - Use
go modfor dependency management.
📌 Quick Reference
Check Go version:
Run program:
Build program:
Format code:
Run tests:
Get dependency:
go versionRun program:
go run main.goBuild program:
go buildFormat code:
go fmt ./...Run tests:
go test ./...Get dependency:
go get package