英文:
Convert String to Array in Golang
问题
我有一个字符串,它来自一个文本文件。我通过 'io/ioutil' 能够获取到它,它包含以下文本:
"[[0, 1], [0, 2], [0,3 ]]"
我该如何将这个字符串转换为一个可以在 for 循环中使用的数组?
英文:
I have a string that is from an text file. I was able to get it via 'io/ioutil' it contains the following text:
"[[0, 1], [0, 2], [0,3 ]]"
How do I convert this string to an array that I can use in a for loop?
答案1
得分: 3
Go是一种严格类型的语言,所以没有像eval语句那样直接将数据转换为代码的功能。在你提到的情况下,考虑到你的列表列表与JSON格式兼容,我想使用JSON包来进行解析。所以只需要三行代码,定义预期的数据类型,从字符串创建解码器,然后将解码器应用于数据类型。Go是严格类型的但支持反射(在这段代码中看不到),这是我花了一些时间适应的原因。反射使得第三行代码成为可能,也是为什么第一行将变量定义为列表列表([][]int)的原因。
package main
import (
"encoding/json"
"fmt"
"strings"
)
// 输出:
// <nil> [[0 1] [0 2] [0 3]]
// 0 0 0
// 0 1 1
// 1 0 0
// 1 1 2
// 2 0 0
// 2 1 3
func main() {
jsonstring := "[[0, 1], [0, 2], [0,3 ]]"
var listoflists [][]int
dec := json.NewDecoder(strings.NewReader(jsonstring))
err := dec.Decode(&listoflists)
fmt.Println(err, listoflists)
for i, list := range listoflists {
for j, value := range list {
fmt.Println(i, j, value)
}
}
}
英文:
Go is a strictly typed language so there isn't something like an eval statement that turns data into code directly. In this case that you asked about, seeing that your list of lists is in a format compatible with the JSON format, I thought of using the JSON package to do the parsing. So it takes only three lines of code, defining the type of data that is expected, creating the decoder from the string, and applying the decoder to the data type. The fact that Go is strictly typed but supports reflection (which you won't see in this code) is what took me a little time to get used to. Reflection is what makes the third line possible and why the first line defines the variable as a list of lists ([][]int).
package main
import (
"encoding/json"
"fmt"
"strings"
)
// Prints:
// <nil> [[0 1] [0 2] [0 3]]
// 0 0 0
// 0 1 1
// 1 0 0
// 1 1 2
// 2 0 0
// 2 1 3
func main() {
jsonstring := "[[0, 1], [0, 2], [0,3 ]]"
var listoflists [][]int
dec := json.NewDecoder(strings.NewReader(jsonstring))
err := dec.Decode(&listoflists)
fmt.Println(err, listoflists)
for i, list := range listoflists {
for j, value := range list {
fmt.Println(i, j, value)
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论