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?
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?
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)
}
}
}