如何将int slice的字符串转换为int slice? [英] How do I convert string of int slice to int slice?
本文介绍了如何将int slice的字符串转换为int slice?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
示例输入:(类型:string
)
"[156, 100, 713]"
转换示例:(类型:int
的切片)
Example conversion: (type: slice of int
)
[156, 100, 713]
推荐答案
除了mhutter的回答,还请注意您输入的string
看起来像一个JSON数组(也许是来自JSON文本?).
In addition to mhutter's answer, also note that your input string
looks like a JSON array (maybe it is from a JSON text?).
如果这样处理,则可以将其内容编组为[]int
片.直接从中解析数字的速度不会更快(如 encoding/json
包使用反射),但肯定更简单:
If you treat it like that, you may unmarshal its content into an []int
slice. This won't be faster that directly parsing the numbers from it (as the encoding/json
package uses reflection), but it is certainly simpler:
s := "[156, 100, 713]"
var is []int
if err := json.Unmarshal([]byte(s), &is); err != nil {
panic(err)
}
fmt.Println(is)
fmt.Printf("%#v", is)
输出(在转到操场上尝试):
[156 100 713]
[]int{156, 100, 713}
这篇关于如何将int slice的字符串转换为int slice?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文