In this article, we will see how to check if a variable is an array or slice in Golang.

To determine if a variable is an array or slice using reflection, we can use the “reflect” package in Golang. Using the reflections, we can inspect the variables at runtime.

Following is an example which shows if the variable is an array or slice by using reflection.

package main

import (
    "fmt"
    "reflect"
)

func main() {
    // Creating an array and a slice
    myArray := [3]int{1, 2, 3}
    mySlice := []int{4, 5, 6}

    // Determining if a variable is an array or slice using reflection
    fmt.Println("myArray is an array:", reflect.TypeOf(myArray).Kind() == reflect.Array)
    fmt.Println("mySlice is a slice:", reflect.TypeOf(mySlice).Kind() == reflect.Slice)
}

Ouput

myArray is an array: true
mySlice is a slice: true

In the above example, The “reflect.TypeOf” function returns the type of the variable, and the “Kind” method returns the basic type of the variable.

We check if the “Kind” of the variable is equal to “reflect.Array” to determine if it is an array, and “reflect.Slice” to determine if it is a slice.

Categorized in:

Tagged in: