0

I want to write a function that can convert slice([]int, []string, []bool, []int64, []float64) to string.

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

There is my code:

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

But it's a little complicated, if i can convert interface{}(type is slice) to []interface{} or get element , it's getting more simple.

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

1 Answer 1

1

You can't do that, because a slice of int, string or anything can't be directly casted to a slice of interfaces. (see that question for more explanation on this).

To do the conversion, you need to cast each item of the slice as an interface{} separately. And you can't access the items without casting to a slice first, but for that you need to know the slice's type (so we're back to square one).

One way to shorten your syntax is to take in a slice of interfaces as argument, and let the caller do the conversion (because the caller knows the slice's type). Here is an example : https://play.golang.org/p/6yLYk1OM25

package main import ( "fmt" "strings" ) func main() { mySlice := []int{1, 2, 3} interfaceSlice := make([]interface{}, len(mySlice)) for index := range mySlice { interfaceSlice[index] = mySlice[index] } fmt.Println(sliceToString(interfaceSlice)) } func sliceToString(values []interface{}) string { s := make([]string, len(values)) // Pre-allocate the right size for index := range values { s[index] = fmt.Sprintf("%v", values[index]) } return strings.Join(s, ",") } 

This will work with any slice as mySlice, but on the way you lose a lot of convenience for the caller.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.