将[][]interface转换为[][]string。

huangapple go评论101阅读模式
英文:

Convert [][]interface to [][]string

问题

有没有简单的方法将[][] interface{}转换为[][]string?我想要将这个[][] interface{}写入一个csv文件,但是go中的writer只接受[][]string类型。额外信息:我的[][] interface{}包含4列,其中2列是字符串,2列是json.Number类型。

提前感谢。

英文:

Is there any easy way to convert [][] interface{} to [][]string ?
What I want is to to write this [][] interface{} to a csv but writer in go accepts only [][]string.
Additional info : my [][] interface{} contains 4 columns 2 of them are string and 2 are json.Number.

Thanks in advance.

答案1

得分: 3

最简单的方法可能是创建新的切片并编写一些循环:

var orig [][]interface{}
var strs = make([][]string, len(orig))
for i := range orig {
   strs[i] = make([]string, len(orig[i]))
   for j := range orig[i]{
     strs[i][j] = fmt.Sprint(orig[i][j])
   }
}
英文:

Simplest way is probably to make new slices and write some loops:

var orig [][]interface{}
var strs = make([][]string, len(orig))
for i := range orig {
   strs[i] = make([]string, len(orig[i]))
   for j := range orig[i]{
     strs[i][j] = fmt.Sprint(orig[i][j])
   }
}

huangapple
  • 本文由 发表于 2017年8月8日 01:08:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/45552207.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定