0

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.

3
  • You can add runtime type assertions. golang.org/ref/spec#Type_assertions. You're using the first form of type assertions, but you can also check whether the assertion succeeds or fails. Also see: stackoverflow.com/questions/28015753/… Commented Jan 23, 2015 at 0:52
  • Yes that is what I'm currently doing. Commented Jan 23, 2015 at 1:02
  • Wouldn't this better be done with a struct type and an attached UnmarshalJSON method (so that it can handle the [] vs {} difference)? Commented Apr 4, 2015 at 20:40

1 Answer 1

1

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)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.