Go Built-in and Standard Library Functions for DSA:

Below is a comprehensive list of all built-in functions in Go, as well as key standard library functions that are particularly relevant to Data Structures and Algorithms (DSA). so I’ll first cover every built-in function predefined in Go (i.e., those available without importing any package), followed by a curated selection of standard library functions from packages like sort, container, and others that are commonly used in DSA contexts. Each function includes a description and a practical example, with a focus on DSA where applicable.


Core Built-in Functions in Go

Go’s built-in functions are predefined and do not require any imports. They are fundamental for manipulating basic data structures (arrays, slices, maps, channels) and handling control flow or memory allocation. Below is the complete list of Go’s built-in functions as per the official Go specification, with examples tailored to DSA where possible.

1. len()

  • Description: Returns the length of a string, array, slice, map, or channel.

  • DSA Use Case: Used to determine the size of data structures, such as finding the midpoint in binary search.

  • Example:

      func binarySearch(arr []int, target int) int {
          low := 0
          high := len(arr) - 1
          for low <= high {
              mid := (low + high) / 2
              if arr[mid] == target {
                  return mid
              } else if arr[mid] < target {
                  low = mid + 1
              } else {
                  high = mid - 1
              }
          }
          return -1
      }
    

2. cap()

  • Description: Returns the capacity of a slice or channel.

  • DSA Use Case: Helps understand the underlying array size of a slice, which can affect resizing operations in dynamic arrays.

  • Example:

      s := make([]int, 0, 10) // length 0, capacity 10
      fmt.Println(cap(s))     // Output: 10
    

3. make()

  • Description: Allocates and initializes slices, maps, or channels.

  • DSA Use Case: Essential for creating dynamic data structures like hash tables (maps) or resizable arrays (slices).

  • Example:

      hashTable := make(map[string]int) // creates a map for a hash table
      hashTable["key"] = 42
      fmt.Println(hashTable["key"])     // Output: 42
    

4. new()

  • Description: Allocates memory for a type and returns a pointer to it, initialized to zero.

  • DSA Use Case: Useful for creating nodes in pointer-based structures like linked lists or trees.

  • Example:

      type Node struct {
          value int
      }
      node := new(Node) // allocates a new Node, returns *Node
      node.value = 10
      fmt.Println(node.value) // Output: 10
    

5. append()

  • Description: Appends elements to a slice, growing it if necessary.

  • DSA Use Case: Used to build dynamic arrays or lists incrementally, such as merging two sorted lists.

  • Example:

      func mergeSlices(a, b []int) []int {
          result := make([]int, 0)
          result = append(result, a...)
          result = append(result, b...)
          return result
      }
    

6. copy()

  • Description: Copies elements from a source slice to a destination slice.

  • DSA Use Case: Useful for duplicating data structures or working with subsets without modifying the original.

  • Example:

      original := []int{1, 2, 3}
      duplicate := make([]int, len(original))
      copy(duplicate, original)
      fmt.Println(duplicate) // Output: [1 2 3]
    

7. delete()

  • Description: Removes an element from a map by key.

  • DSA Use Case: Common in hash table operations to remove key-value pairs.

  • Example:

      hashTable := map[string]int{"key": 1}
      delete(hashTable, "key")
      fmt.Println(hashTable) // Output: map[]
    

8. complex()

  • Description: Constructs a complex number from real and imaginary parts.

  • DSA Use Case: Less common in general DSA but useful in numerical algorithms involving complex numbers.

  • Example:

      c := complex(3, 4) // creates 3 + 4i
      fmt.Println(c)     // Output: (3+4i)
    

9. real()

  • Description: Returns the real part of a complex number.

  • DSA Use Case: Paired with complex() for algorithms involving complex number computations.

  • Example:

      c := complex(3, 4)
      r := real(c)
      fmt.Println(r) // Output: 3
    

10. imag()

  • Description: Returns the imaginary part of a complex number.

  • DSA Use Case: Similar to real(), used in numerical algorithms.

  • Example:

      c := complex(3, 4)
      i := imag(c)
      fmt.Println(i) // Output: 4
    

11. panic()

  • Description: Triggers a run-time panic, halting normal execution.

  • DSA Use Case: Not directly used in DSA but useful for error handling in algorithm implementations.

  • Example:

      if someCondition {
          panic("algorithm failed")
      }
    

12. recover()

  • Description: Stops a panic and returns the value passed to panic().

  • DSA Use Case: Ensures robustness in algorithms by recovering from unexpected failures.

  • Example:

      defer func() {
          if r := recover(); r != nil {
              fmt.Println("Recovered:", r)
          }
      }()
      panic("something went wrong")
    

13. print() and println()

  • Description: Debugging functions that print arguments to standard error (not recommended for production).

  • DSA Use Case: Handy for quick debugging during algorithm development.

  • Example:

      print("Debug: ", 42, "\n") // prints to stderr
      println("Debug:", 42)      // prints with newline
    

14. close()

  • Description: Closes a channel to indicate no more values will be sent.

  • DSA Use Case: Useful in concurrent algorithms using channels as queues or pipelines.

  • Example:

      ch := make(chan int)
      go func() {
          ch <- 1
          close(ch)
      }()
      val, ok := <-ch
      fmt.Println(val, ok) // Output: 1 true
    

Standard Library Functions for DSA

Since the user requested "all that is literally out there," I’ll also include key functions from Go’s standard library that are widely used in DSA. These require imports but are integral to implementing algorithms and data structures beyond what the core built-ins provide. I’ll focus on the sort, container, and a few other relevant packages.

From the sort Package

The sort package provides sorting and searching utilities.

  1. sort.Slice()

    • Description: Sorts a slice using a custom less function.

    • DSA Use Case: Flexible sorting for custom data structures.

    • Example:

        import "sort"
        type Person struct {
            Name string
            Age  int
        }
        people := []Person{{"Alice", 30}, {"Bob", 25}}
        sort.Slice(people, func(i, j int) bool {
            return people[i].Age < people[j].Age
        })
      
  2. sort.Ints()

    • Description: Sorts a slice of integers.

    • DSA Use Case: Quick sorting of integer arrays.

    • Example:

        import "sort"
        ints := []int{3, 1, 4}
        sort.Ints(ints)
        fmt.Println(ints) // Output: [1 3 4]
      
  3. sort.Float64s()

    • Description: Sorts a slice of float64 values.

    • DSA Use Case: Sorting floating-point data.

    • Example:

        import "sort"
        floats := []float64{3.14, 1.41, 2.71}
        sort.Float64s(floats)
        fmt.Println(floats) // Output: [1.41 2.71 3.14]
      
  4. sort.Strings()

    • Description: Sorts a slice of strings.

    • DSA Use Case: Lexicographical sorting of string data.

    • Example:

        import "sort"
        strings := []string{"go", "python", "java"}
        sort.Strings(strings)
        fmt.Println(strings) // Output: [go java python]
      
  5. sort.Search()

    • Description: Performs a binary search on a sorted slice.

    • DSA Use Case: Efficient searching (O(log n)).

    • Example:

        import "sort"
        sorted := []int{1, 2, 3, 4, 5}
        index := sort.Search(len(sorted), func(i int) bool {
            return sorted[i] >= 3
        })
        fmt.Println(index) // Output: 2
      

From the container Package

The container package provides implementations of common data structures.

  1. container/list

    • Description: Implements a doubly-linked list.

    • DSA Use Case: Queues, stacks, or list-based algorithms.

    • Example:

        import "container/list"
        l := list.New()
        l.PushBack(1)
        l.PushBack(2)
        for e := l.Front(); e != nil; e = e.Next() {
            fmt.Println(e.Value)
        }
        // Output: 1 2
      
  2. container/heap

    • Description: Provides heap operations for any type implementing heap.Interface.

    • DSA Use Case: Priority queues and heap-based algorithms.

    • Example:

        import "container/heap"
        type IntHeap []int
        func (h IntHeap) Len() int           { return len(h) }
        func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }
        func (h IntHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
        func (h *IntHeap) Push(x interface{}) { *h = append(*h, x.(int)) }
        func (h *IntHeap) Pop() interface{} {
            old := *h
            n := len(old)
            x := old[n-1]
            *h = old[0 : n-1]
            return x
        }
        h := &IntHeap{2, 1, 5}
        heap.Init(h)
        heap.Push(h, 3)
        fmt.Println(heap.Pop(h)) // Output: 5 (max heap)
      
  3. container/ring

    • Description: Implements a circular list.

    • DSA Use Case: Round-robin scheduling or cyclic buffers.

    • Example:

        import "container/ring"
        r := ring.New(3)
        for i := 0; i < 3; i++ {
            r.Value = i
            r = r.Next()
        }
        r.Do(func(p interface{}) {
            fmt.Println(p.(int))
        })
        // Output: 0 1 2
      

From Other Packages

These packages provide utilities that enhance DSA implementations.

  1. math/rand

    • Description: Generates random numbers.

    • DSA Use Case: Randomized algorithms (e.g., quicksort).

    • Example:

        import "math/rand"
        import "time"
        rand.Seed(time.Now().UnixNano())
        random := rand.Intn(100)
        fmt.Println(random) // Random int between 0 and 99
      
  2. sync (e.g., sync.Mutex)

    • Description: Provides synchronization primitives.

    • DSA Use Case: Ensures thread safety in concurrent algorithms.

    • Responsive

        import "sync"
        var mu sync.Mutex
        counter := 0
        mu.Lock()
        counter++
        mu.Unlock()
      
  3. time (e.g., time.Now(), time.Since())

    • Description: Measures time.

    • DSA Use Case: Benchmarks algorithm performance.

    • Example:

        import "time"
        start := time.Now()
        // Simulate algorithm
        time.Sleep(100 * time.Millisecond)
        elapsed := time.Since(start)
        fmt.Println(elapsed) // Output: ~100ms
      

Notes on Completeness

  • Built-in Functions: The list above (len, cap, make, new, append, copy, delete, complex, real, imag, panic, recover, print, println, close) represents all built-in functions in Go as defined in the language specification. There are no additional built-ins beyond these.

  • Standard Library: While Go’s standard library contains hundreds of functions across many packages (e.g., fmt, os, net/http), I’ve focused on those most relevant to DSA (sort, container, math/rand, sync, time). Including every standard library function would be impractical and beyond the DSA scope, but the ones listed are the most commonly used in algorithmic contexts.

  • Examples: Each function has a practical example, with a DSA focus where applicable. For functions like print or complex, which are less directly tied to DSA, I’ve provided general usage examples.

0
Subscribe to my newsletter

Read articles from Oluwagbenga Fagbola directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Oluwagbenga Fagbola
Oluwagbenga Fagbola

ENGINEER.