Golang — Utility functions you always missed

A set of utility functions, to let you use what is not provided inbuilt by Golang...
Feb 21 2022 · 5 min read

DRY — Do not repeat yourself

Save your time by using some common codes, without implementing them separately. Here is a list of some generally used utility function implementations.


1. Check whether an element exists in the array or not

Golang doesn’t have a pre-defined function to check element existence inside an array. The following code snippet does the same job for you.

import "fmt"

func main() {
  // create an array of strings
  slice := []string{"apple", "grapes", "mango"}
  // You can check by changing element to "orange"
  if Contains(slice, "mango") { 
    fmt.Println("Slice contains element")
  } else {
    fmt.Println("Slice doesn't contain element")
  }
}

func Contains(slice []string, element string) bool {
   for _, i := range slice {
     if i == element {
       return true
     }
   }
   return false
}


// Output
Slice contains element

We looped over the slice and matched the filtering element against the array, if it exists inside the array it will return else false.


2. Check if the given time belongs between two timestamps or not

Use the below function to check whether the given time belongs between two timestamps or not.

import (
 "time"
 "fmt"
)

func main() {
  currentTime := time.Now() 
  // Time after 18 hours of currentTime
  futureTime := time.Now().Add(time.Hour * 18) 
  // Time after 10 hours of currentTime
  intermediateTime := time.Now().Add(time.Hour * 10) 
  if intermediateTime.After(currentTime) &&    intermediateTime.Before(futureTime) {
    fmt.Println("intermediateTime is between currentTime and  futureTime")
  } else {
    fmt.Println("intermediateTime is not inbetween currentTime and futureTime")
  }
}


// Output:
intermediateTime is between currentTime and futureTime

Given two timestamps for checking whether current-time is residing between the two. Golang time package is providing an inbuilt function to check it. We used .After() and .Before() methods if both are true then we can admit that the current time is between given times.


3. Find the current timestamp of a specific timezone

The following code snippet will give you currentTime inside a specific timezone.

import (
 "time"
 "fmt"
)

func main() {
  timeZone := "Asia/Kolkata" // timezone value
  loc, _ := time.LoadLocation(timeZone)
  currentTime = time.Now().In(loc)
  fmt.Println("currentTime : ", currentTime)
}


//Output:

// for timezone = "Asia/Kolkata"
currentTime :  2022-02-09 10:42:39.164079505 +0530 IST
// for timezone = "Asia/Shanghai"
currentTime :  2022-02-09 13:14:33.986953939 +0800 CST

First load Location of given timezone using time.LoadLocation(), then use it with time.Now.In(), to get the current time in a given timezone. you can modify the value of the timeZone variable to the desired one.


4. Divide a smaller number with a larger one

If you divide a smaller integer by a larger one, it gives 0 as a result, use the below alternative as a solution.

import "fmt"

func main() {
  smallerNo := 5
  largerNo := 25
  result := float32(smallerNo) / float32(largerNo)
  fmt.Println("result : ", result)
}


// Output:
result : 0.2

Convert both the numbers to float and then divide them, it will produce a true result of division.


5. Remove duplicates from an array

Check the below solution, to remove duplications from the slice of strings.

import "fmt"


func main() {
  // define array of strings
  fruits := []string{"Mango", "Grapes", "Kiwi", "Apple", "Grapes"}
  fmt.Println("Array before removing duplicates : ", fruits)
  // Array after duplicates removal
  dulicatesRemovedArray := RemoveDuplicatesFromSlice(fruits)
  fmt.Println("Array after removing duplicates : ",  dulicatesRemovedArray)
}

func RemoveDuplicatesFromSlice(intSlice []string) []string {
  keys := make(map[string]bool)
  list := []string{}
  for _, entry := range intSlice {
    if _, value := keys[entry]; !value {
      keys[entry] = true
      list = append(list, entry)
    }
  }
 return list
}


// Output:
Array before removing duplicates :  [Mango Grapes Kiwi Apple Grapes]
Array after removing duplicates :  [Mango Grapes Kiwi Apple]

We have defined another slice and assigned the first values by checking if the value already exists in the new slice or not. It returns the slice without duplicates.


6. How to shuffle an array

Golang doesn’t have an inbuilt function for shuffling array elements, find the below snippet to perform shuffling.

import "fmt"

func main() {
  // shuffle array
  array := []string{"India", "US", "Canada", "UK"}
  Shuffle(array)
}

func Shuffle(array []string) {
  // seed random for changing order of elements
  random := rand.New(rand.NewSource(time.Now().UnixNano()))
  for i := len(array) - 1; i > 0; i-- {
     j := random.Intn(i + 1)
     array[i], array[j] = array[j], array[i]
  }
  fmt.Println("Shuffled array : ", array)
}


// Output: 
Shuffled array :  [UK India Canada US]

To shuffle elements inside an array, we must use random and then swap elements.


7. Reverse an array

Reversing an array is not directly available unless you use some library, use the below function to revert a slice.

import "fmt"


func main() {
  a := []int{1, 2, 3, 4, 5, 6} // input int array
  reverseArray := ReverseSlice(a)
  fmt.Println("Reverted array : ", reverseArray) // print output
}

func ReverseSlice(a []int) []int {
  for i := len(a)/2 - 1; i >= 0; i-- {
   pos := len(a) - 1 - i
   a[i], a[pos] = a[pos], a[i]
}
 return a
}


// Output: 
Reverted array :  [6 5 4 3 2 1]

Divide the array from the middle(length/2) and swap two of the positions across the borderline with the help of the pos variable. i.e. if you have array of length 6 then swapping will be done in order of array[2] <-> array[3], array[1] <-> array[4] and array[0] <-> array[5].


8. Sum slice elements

find the sum of slice elements using the below function.

import "fmt"


func main() {
  s := []int{10, 20, 30}
  sum := sumSlice(s)
  fmt.Println("Sum of slice elements : ", sum)
}


func sumSlice(array []int) int {
  sum := 0
  for _, item := range array {
      sum += item
  }
  return sum
}


// Output:
Sum of slice elements :  60

Loop over a slice and add it to the previous result. This will give a sum of slice elements.


9. Convert a slice to a comma-separated string

The below code converts the given slice to comma-separated strings.

import (
   "fmt"
   "strings"
   "strconv"
)


func main() {
   result := ConvertSliceToString([]int{10, 20, 30, 40})
   fmt.Println("Slice converted string : ", result)
}


func ConvertSliceToString(input []int) string {
   var output []string
   for _, i := range input {
      output = append(output, strconv.Itoa(i))
   }
   return strings.Join(output, ",")
}


// Output:
Slice converted string :  10,20,30,40

Given a slice as input, loop over it and add it to a string array, then join the produced string array with a comma(,).


10. Convert the given string to snake_case

The below snippet will convert the given string into a snake case. However it can be done with the help of a library, it’s also feasible without library usage.

import (
  "fmt"
  "strings"
  "regexp"
)


func main() {
   snakeCase := ConvertToSnakeCase("ILikeProgrammingINGo123")
   fmt.Println("String in snake case : ", snakeCase)
}


func ConvertToSnakeCase(input string) string {
  var matchChars = regexp.MustCompile("(.)([A-Z][a-z]+)")
  var matchAlpha = regexp.MustCompile("([a-z0-9])([A-Z])")
  
  snake := matchChars.ReplaceAllString(input, "${1}_${2}")
  snake = matchAlpha.ReplaceAllString(snake, "${1}_${2}")
  return strings.ToLower(snake)
}


// Output:
String in snake case :  i_like_programming_in_go123

Compile regex with alphabets, digits, and special characters then replace the given string to underscore(_) with compiled regex. It will add _ at the required position.

Find full source code at Utility functions in Golang.

Keep coding !!


Similar Articles


nidhi-d image
Nidhi Davra
Web developer@canopas | Gravitated towards Web | Eager to assist


nidhi-d image
Nidhi Davra
Web developer@canopas | Gravitated towards Web | Eager to assist

contact-footer
Say Hello!
footer
Subscribe Here!
Follow us on
2024 Canopas Software LLP. All rights reserved.