I have a function that is passed a map, each element of which needs to be handled differently depending on whether it is a primitive or a slice. The type of the slice is not known ahead of time. How can I determine which elements are slices (or arrays) and which are not?
The basic difference between a slice and an array is that a slice is a reference to a contiguous segment of an array. Unlike an array, which is a value-type, slice is a reference type. A slice can be a complete array or a part of an array, indicated by the start and end index.
isArray(variableName) method to check if a variable is an array. The Array. isArray(variableName) returns true if the variableName is an array. Otherwise, it returns false .
JavaScript Array slice()The slice() method returns selected elements in an array, as a new array. The slice() method selects from a given start, up to a (not inclusive) given end. The slice() method does not change the original array.
How to check if a slice contains an element. To check if a particular element is present in a slice object, we need to perform the following steps: Use a for loop to iterate over each element in the slice . Use the equality operator ( == ) to check if the current element matches the element you want to find.
Have a look at the reflect
package.
Here is a working sample for you to play with.
package main
import "fmt"
import "reflect"
func main() {
m := make(map[string]interface{})
m["a"] = []string{"a", "b", "c"}
m["b"] = [4]int{1, 2, 3, 4}
test(m)
}
func test(m map[string]interface{}) {
for k, v := range m {
rt := reflect.TypeOf(v)
switch rt.Kind() {
case reflect.Slice:
fmt.Println(k, "is a slice with element type", rt.Elem())
case reflect.Array:
fmt.Println(k, "is an array with element type", rt.Elem())
default:
fmt.Println(k, "is something else entirely")
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With