Golang Useful function/code

by DonOfDen


Posted on 11 Sep 2019

Tags: golang useful-code function code Go


Here are some of the useful functions/code, I’ve gathered from my personal experiences with dealing Go code.

Awesome Go

Free APIs for mini projects

Convert int8 to bool in golang

// IntToBool returns bool for int
func IntToBool(i int) bool {
    if i == 1 {
        return true
    }
    return false
}

Try in Go Playground

Convert value to bool in golang

// ValueToBool returns bool for interface
func ValueToBool(i interface{}) bool {
    if i == 1 {
        return true
    }
    return false
}

Convert bool to unsigned integer in golang

uint

// ValueToBool returns bool for interface
func bool2int(a bool) uint64 {
    return *(*uint64)(unsafe.Pointer(&a)) & 1
}

Try in Go Playground

Compare two slice elements and check if they are equal - IsSliceEqual

// IsSliceEqual tells whether a and b contain the same elements. A nil argument is equivalent to an empty slice.
// Returns a boolean if data is available/not
func IsSliceEqual(a, b []string) bool {
	if len(a) != len(b) {
		return false
	}
	for i, v := range a {
		if v != b[i] {
			return false
		}
	}
	return true
}

Try in Go Playground

Check if value is in slice - stringInSlice

// There is no built-in operator to do it in Go. You need to iterate over the array. 
// Returns a boolean if string is available/not
func stringInSlice(a string, list []string) bool {
    for _, b := range list {
        if b == a {
            return true
        }
    }
    return false
}

Try in Go Playground