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.
// IntToBool returns bool for int
func IntToBool(i int) bool {
if i == 1 {
return true
}
return false
}
// ValueToBool returns bool for interface
func ValueToBool(i interface{}) bool {
if i == 1 {
return true
}
return false
}
// ValueToBool returns bool for interface
func bool2int(a bool) uint64 {
return *(*uint64)(unsafe.Pointer(&a)) & 1
}
// 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
}
// 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
}