go - golang - how to get element from the interface{} type of slice? -


i want write function can convert slice([]int, []string, []bool, []int64, []float64) string.

[]string{a,b,c} -> a,b,c []int{1,2,3}    -> 1,2,3 

there code:

func slicetostring(itr interface{}) string {     switch itr.(type) {     case []string:         return strings.join(itr.([]string), ",")     case []int:         s := []string{}         _, v := range itr.([]int) {             s = append(s, fmt.sprintf("%v", v))         }         return strings.join(s, ",")     case []int64:         s := []string{}         _, v := range itr.([]int64) {             s = append(s, fmt.sprintf("%v", v))         }         return strings.join(s, ",")     case []float64:         s := []string{}         _, v := range itr.([]float64) {             s = append(s, fmt.sprintf("%v", v))         }         return strings.join(s, ",")     case []bool:         s := []string{}         _, v := range itr.([]bool) {             s = append(s, fmt.sprintf("%v", v))         }         return strings.join(s, ",")     }      return "" } 

but it's little complicated, if can convert interface{}(type slice) []interface{} or element , it's getting more simple.

 func slicetostring(itr interface{}) string {     s := []string{}     // convert interface{} []interface{} or elements     // els := ...     _,v:= range els{        s = append(s, fmt.sprintf("%v", v))     }     return s  } 

you can't that, because slice of int, string or can't directly casted slice of interfaces. (see that question more explanation on this).

to conversion, need cast each item of slice interface{} separately. , can't access items without casting slice first, need know slice's type (so we're square one).

one way shorten syntax take in slice of interfaces argument, , let caller conversion (because caller knows slice's type). here example : https://play.golang.org/p/6ylyk1om25

package main  import (     "fmt"     "strings" )  func main() {     myslice := []int{1, 2, 3}      interfaceslice := make([]interface{}, len(myslice))     index := range myslice {         interfaceslice[index] = myslice[index]     }      fmt.println(slicetostring(interfaceslice)) }  func slicetostring(values []interface{}) string {     s := make([]string, len(values)) // pre-allocate right size     index := range values {         s[index] = fmt.sprintf("%v", values[index])     }     return strings.join(s, ",") } 

this work slice myslice, on way lose lot of convenience caller.


Comments

Popular posts from this blog

php - Invalid Cofiguration - yii\base\InvalidConfigException - Yii2 -

How to show in django cms breadcrumbs full path? -

ruby on rails - npm error: tunneling socket could not be established, cause=connect ETIMEDOUT -