Skip to content

Go System Utilities

Go provides powerful packages for common system-level tasks like sorting data, writing tests, and interacting with the Operating System.

1. Sorting (sort package)

Go's sort package is highly optimized for sorting slices of any built-in or custom type.

package main

import (
    "fmt"
    "sort"
)

func main() {
    // Sorting built-ins
    strs := []string{"c", "a", "b"}
    sort.Strings(strs)
    fmt.Println("Strings:", strs)

    ints := []int{7, 2, 4}
    sort.Ints(ints)
    fmt.Println("Ints:   ", ints)

    // Checking if sorted
    s := sort.IntsAreSorted(ints)
    fmt.Println("Sorted: ", s)
}

2. Testing (testing package)

Go has a built-in testing framework. Files must end in _test.go and functions must start with Test.

1
2
3
4
5
6
7
// main_test.go
func TestAdd(t *testing.T) {
    ans := Add(2, -2)
    if ans != 0 {
        t.Errorf("Add(2, -2) = %d; want 0", ans)
    }
}
Run with: go test

3. Benchmarking

You can measure the performance of your code using benchmark functions.

1
2
3
4
5
func BenchmarkAdd(b *testing.B) {
    for i := 0; i < b.N; i++ {
        Add(1, 2)
    }
}
Run with: go test -bench=.

4. Executing Processes (os/exec)

You can run external commands (like ls or grep) directly from Go.

import "os/exec"

func main() {
    // 1. Simple command
    dateCmd := exec.Command("date")
    dateOut, _ := dateCmd.Output()
    fmt.Println("> date")
    fmt.Println(string(dateOut))

    // 2. Command with arguments
    grepCmd := exec.Command("grep", "hello")
}

5. Signals (os/signal)

Use signals to handle events like Ctrl+C (SIGINT) for a graceful shutdown.

1
2
3
4
5
6
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)

// Block until a signal is received
sig := <-sigs
fmt.Println("Received signal:", sig)

Summary Table

Package Purpose
sort Functions for sorting slices and user-defined collections.
testing Automated testing of Go packages.
os/exec Running external commands.
os/signal Access to incoming Unix signals.