Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you determine if a variable is a slice or array?

Tags:

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?

like image 228
Max Avatar asked Apr 25 '14 23:04

Max


People also ask

What is the difference between array and slice?

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.

How do you check if a variable is an array?

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 .

Is a slice an array?

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 do I check my slice data?

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.


1 Answers

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")
        }
    }
}
like image 167
jimt Avatar answered Oct 19 '22 15:10

jimt