0
我想寫一個函數,可以將slice([] int,[] string,[] bool,[] int64,[] float64)轉換爲字符串。golang - 如何從界面{}類型的切片中獲取元素?
[]string{a,b,c} -> a,b,c
[]int{1,2,3} -> 1,2,3
還有就是我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 ""
}
但它是一個有點複雜,如果我可以轉換接口{}(類型片)爲[]接口{}或獲取元素,它變得更簡單。
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
}