I have an array (coming from JSON) that always contains a string and an int, like so: ["foo",42]
Right now, I have to use []interface{}
with assertions arr[0].(string)
arr[1].(int)
I'm wondering if there's any way to specify the types expected in the array? I'm picturing something like.. [...]{string,int}
Thanks.
At the first, answer is No. But you can get values from interface{}
with type you expected. How about this?
package main
import (
"encoding/json"
"fmt"
"github.com/mattn/go-scan"
"log"
)
func main() {
text := `["foo", 42]`
var v interface{}
err := json.Unmarshal([]byte(text), &v)
if err != nil {
log.Fatal(err)
}
var key string
var val int
e1, e2 := scan.ScanTree(v, "[0]", &key), scan.ScanTree(v, "[1]", &val)
if e1 != nil || e2 != nil {
log.Fatal(e1, e2)
}
fmt.Println(key, val)
}