← Back to Index

Go Reference

0. Basics

0.1 Hello World

package main

import "fmt"

func main() {
    // fmt.Println prints to STDOUT with a newline
    fmt.Println("Hello, World!")
}
TERMINAL OUTPUT
Hello, World!

0.2 Building & Running

# Compile to a binary using go build
go build main.go

# Run the generated binary
./main

# Compile and run in one step using go run
go run main.go
TERMINAL OUTPUT
Hello, World!

0.3 Comments

// Single-line comment for brief notes

/* Multi-line
   comment block for detailed explanations */
TERMINAL OUTPUT
(No output)

0.4 Imports

import (
    "fmt"
    "os"
    "net/http"
    m "math" // Aliasing a module for shorter access
)
TERMINAL OUTPUT
(No output)

0.5 Exit Codes

import "os"

func main() {
    // Exit immediate with status code (non-zero indicates error)
    os.Exit(1) 
}
TERMINAL OUTPUT
(Process exits with status 1)

0.6 Error Handling

Go uses explicit return values for errors.

import (
    "errors"
    "fmt"
)

// Function returning an integer and an error
func doWork() (int, error) {
    return 0, errors.New("something went wrong")
}

func main() {
    val, err := doWork()
    // Explicitly check if error is not nil
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(val)
}
TERMINAL OUTPUT
something went wrong

1. Environment, Variables & Time

1.1 Variable Declaration

var a int = 1 // Explicit variable declaration with type
b := 2        // Short-hand declaration with type inference (only inside functions)
const C = 3   // Immutable constant value
TERMINAL OUTPUT
(No output)

1.2 Integer Types & Limits

Size Signed Unsigned
8-bit int8 uint8 (byte)
32-bit int32 (rune) uint32
Arch int uint

Limits: math.MaxInt32, math.MaxUint64.

1.3 Casting

Numeric conversion is explicit in Go.

i := 42
f := float64(i) // Convert int to float64
u := uint(f)    // Convert float64 to uint
TERMINAL OUTPUT
(No output)

1.4 Environment Variables

import "os"

// Retrieve an environment variable
val := os.Getenv("PATH")
// Set an environment variable for the current process
os.Setenv("KEY", "VALUE")
TERMINAL OUTPUT
(No output)

1.5 Time Measurement & Formatting

import (
    "fmt"
    "time"
)

func main() {
    // High-resolution measurement
    start := time.Now()
    elapsed := time.Since(start)

    // Formatting using reference date: Mon Jan 2 15:04:05 MST 2006
    now := time.Now()
    fmt.Println(now.Format(time.RFC3339))
    fmt.Println(now.Format("2006-01-02 15:04:05"))
}
TERMINAL OUTPUT
2024-05-16T12:00:00Z (example)
2024-05-16 12:00:00 (example)

2. Operators & Regex

2.1 Arithmetic & Logic

sum := 10 + 3 // Addition (13)
div := 10 / 3 // Integer division (3)
fDiv := 10.0 / 3.0 // Floating point division (3.33)
res := true && false // Logical AND (false)
TERMINAL OUTPUT
(No output)

2.2 Regex & Pattern Matching

import (
    "fmt"
    "regexp"
)

func main() {
    // Compile regex pattern
    re := regexp.MustCompile(`\$(\d+)`)
    // Find submatches in input string
    match := re.FindStringSubmatch("Price: $100")
    if len(match) > 1 {
        fmt.Println(match[1]) // Print first captured group: "100"
    }
}
TERMINAL OUTPUT
100

3. Argument Parsing

3.1 Argument Parsing

import (
    "flag"
    "fmt"
)

func main() {
    // Define command-line flags
    verb := flag.Bool("v", false, "verbose mode")
    name := flag.String("name", "user", "target username")

    // Parse defined flags from os.Args[1:]
    flag.Parse()
    
    // Retrieve remaining positional arguments
    args := flag.Args()
    fmt.Printf("Verbose: %v, Name: %s\n", *verb, *name)
}
TERMINAL OUTPUT
Verbose: false, Name: user

4. Functions & Memory

4.1 Declaration & Returns

// Basic function with integer return
func add(a, b int) int { return a + b }

// Multi-return function
func swap(a, b int) (int, int) { return b, a }

// Named returns for clearer documentation
func split(sum int) (x, y int) {
    x = sum * 4 / 9
    y = sum - x
    return // Returns current values of x and y
}
TERMINAL OUTPUT
(No output)

4.2 References & Pointers

// Function accepting a pointer (*) to an integer
func increment(n *int) {
    *n++ // Dereference pointer to modify original value
}

func main() {
    x := 10
    increment(&x) // Pass memory address (&) of x
}
TERMINAL OUTPUT
(No output)

5. Control Flow

5.1 Conditionals (If/Else)

Standard branching logic. Go has no implicit truthiness; conditions must be bool.

x := 10
if x > 5 {
    fmt.Println("Greater")
} else if x == 5 {
    fmt.Println("Equal")
} else {
    fmt.Println("Less")
}
TERMINAL OUTPUT
Greater

5.2 Switch / Case

Go uses the switch statement for multi-way branching.

val := 2
switch val {
case 1:
    fmt.Println("One")
case 2, 3:
    fmt.Println("Two or Three")
default:
    fmt.Println("Other")
}
TERMINAL OUTPUT
Two or Three

5.3 Basic Loops (While/For)

Go uses the for keyword for all loops.

// Standard C-style for loop
for i := 0; i < 3; i++ {
    fmt.Printf("for: %d\n", i)
}

x := 0
// While-style loop (condition only)
for x < 3 {
    fmt.Printf("while: %d\n", x)
    x++
}
TERMINAL OUTPUT
for: 0
for: 1
for: 2
while: 0
while: 1
while: 2

5.4 Breaking & Continue

Controlling loop flow.

for i := 0; i < 10; i++ {
    if i < 2 { continue } // Skip iteration
    if i == 5 { break }    // Exit loop
    fmt.Println(i)
}
TERMINAL OUTPUT
2
3
4

5.5 Iterating Collections

Accessing elements in slices or maps using range.

// Slices iteration using range
for index, val := range []int{10, 20} {
    fmt.Printf("%d: %d\n", index, val)
}

// Maps iteration using range
m := map[string]int{"a": 1}
for key, val := range m {
    fmt.Printf("%s: %d\n", key, val)
}
TERMINAL OUTPUT
0: 10
1: 20
a: 1

6. Strings & Files

6.1 String Manipulation

import (
    "fmt"
    "strings"
)

func main() {
    s := " Hello "
    s = strings.TrimSpace(s) // "Hello"
    sub := s[0:2] // Slice substring "He"
    joined := strings.Join([]string{"a", "b"}, "-") // "a-b"
}
TERMINAL OUTPUT
(No output)

6.2 Path Joining

import (
    "fmt"
    "path/filepath"
)

func main() {
    // OS-agnostic path building
    p := filepath.Join("/", "usr", "bin")
    fmt.Println(p)
}
TERMINAL OUTPUT
/usr/bin

6.3 Streaming I/O (Chunks)

import (
    "os"
    "io"
)

func main() {
    f, _ := os.Open("file.bin")
    defer f.Close() // Ensure file is closed on exit
    buf := make([]byte, 4096) // 4KB buffer
    for {
        n, err := f.Read(buf)
        if err == io.EOF { break } // End of file
        // Process buf[:n]
    }
}
TERMINAL OUTPUT
(No output)

6.4 Read to Memory

import "os"

func main() {
    // Read entire file content into a byte slice
    bytes, _ := os.ReadFile("file.txt")
}
TERMINAL OUTPUT
(No output)

7. Binary & Bitwise

7.1 Allocation & Packing

import "encoding/binary"

func main() {
    buf := make([]byte, 4)
    // Pack 32-bit unsigned integer into buffer using Big-Endian
    binary.BigEndian.PutUint32(buf, 42)
}
TERMINAL OUTPUT
(No output)

7.2 Bitwise Operations

res := 0b1010 & 0b1100 // Bitwise AND
res = 0b1010 | 0b1100  // Bitwise OR
res = 0b1010 ^ 0b1100  // Bitwise XOR
res = ^0b1010          // Bitwise NOT (complement)
res = 0b0001 << 2      // Bitwise Shift Left (0b0100)
TERMINAL OUTPUT
(No output)

7.3 Hex Conversion

import (
    "fmt"
    "strconv"
)

func main() {
    // Format integer as hex string
    s := fmt.Sprintf("%x", 255) // "ff"
    // Parse hex string back to integer (64-bit)
    val, _ := strconv.ParseInt("ff", 16, 64) // 255
}
TERMINAL OUTPUT
(No output)

8. Collections & JSON

8.1 Lists, Maps & Sets

// Slice (Dynamic List)
l := []int{1, 2}; l = append(l, 3) 
// Map (Key-Value pairs)
m := make(map[string]int); m["k"] = 1 
// Set behavior implemented using map with empty struct
s := make(map[int]struct{}); s[1] = struct{}{} 
TERMINAL OUTPUT
(No output)

8.2 JSON Parsing

import (
    "encoding/json"
    "fmt"
)

func main() {
    type User struct { ID int `json:"id"` }
    var u User
    // Unmarshal JSON byte slice into struct
    json.Unmarshal([]byte(`{"id":42}`), &u)
    fmt.Println(u.ID)
}
TERMINAL OUTPUT
42

9. Systems & Networking

9.1 TCP Server & Client

import (
    "fmt"
    "net"
)

func main() {
    // Listen for incoming TCP connections
    l, _ := net.Listen("tcp", ":8080")
    
    // Connect to a remote TCP server
    conn, _ := net.Dial("tcp", "example.com:80")
    // Write data to the connection
    fmt.Fprintf(conn, "GET / HTTP/1.0\r\n\r\n")
}
TERMINAL OUTPUT
(No output)

9.2 UDP Server & Client

import "net"

func main() {
    // Connect via UDP
    conn, _ := net.Dial("udp", "127.0.0.1:8080")
    // Send datagram payload
    conn.Write([]byte("ping"))
}
TERMINAL OUTPUT
(No output)

9.3 Concurrency

import (
    "fmt"
    "time"
)

func main() {
    // Start a concurrent goroutine
    go func() {
        fmt.Println("Concurrent goroutine")
    }()
    time.Sleep(10 * time.Millisecond) // Give time for goroutine to execute
}
TERMINAL OUTPUT
Concurrent goroutine

9.4 SQLite

import (
    "fmt"
    "os/exec"
)

func main() {
    // Execute sqlite3 CLI command and capture output
    out, _ := exec.Command("sqlite3", ":memory:", "SELECT 42;").Output()
    fmt.Printf("%s", out)
}
TERMINAL OUTPUT
42