gitlab.com/evatix-go/core@v1.3.55/coredata/coredynamic/SliceItemsAsStrings.go (about)

     1  package coredynamic
     2  
     3  import (
     4  	"fmt"
     5  	"reflect"
     6  
     7  	"gitlab.com/evatix-go/core/constants"
     8  	"gitlab.com/evatix-go/core/errcore"
     9  )
    10  
    11  func SliceItemsAsStrings(reflectVal reflect.Value) ([]string, error) {
    12  	if reflectVal.Kind() == reflect.Ptr {
    13  		return SliceItemsAsStrings(
    14  			reflect.Indirect(reflect.ValueOf(reflectVal)))
    15  	}
    16  
    17  	k := reflectVal.Kind()
    18  	isSliceOrArray := k == reflect.Slice ||
    19  		k == reflect.Array
    20  
    21  	if !isSliceOrArray {
    22  		return []string{},
    23  			errcore.TypeMismatchType.Error("Reflection is not Slice or Array", reflectVal)
    24  	}
    25  
    26  	length := reflectVal.Len()
    27  	slice := make([]string, length)
    28  
    29  	if length == 0 {
    30  		return slice, nil
    31  	}
    32  
    33  	for i := 0; i < length; i++ {
    34  		value := reflectVal.Index(i)
    35  		toString := fmt.Sprintf(
    36  			constants.SprintValueFormat,
    37  			value.Interface())
    38  		slice[i] = toString
    39  	}
    40  
    41  	return slice, nil
    42  }