【发布时间】:2015-10-10 03:27:05
【问题描述】:
我想写一个可以将 slice([]int, []string, []bool, []int64, []float64) 转换为字符串的函数。
[]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 ""
}
但这有点复杂,如果我可以将 interface{}(type is slice) 转换为 []interface{} 或 get element ,它会变得更加简单。
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
}
【问题讨论】:
标签: go