包含多个特定类型的固定大小数组?

huangapple go评论109阅读模式
英文:

Fixed-size array that contains multiple specific types?

问题

我有一个数组(来自JSON),它始终包含一个字符串和一个整数,就像这样:["foo", 42]

目前,我必须使用[]interface{}和断言arr[0].(string) arr[1].(int)

我想知道是否有任何方法可以指定数组中期望的类型?我想象中的写法是 [...]{string,int}

谢谢。

英文:

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.

答案1

得分: 1

首先,答案是否定的。但是你可以使用期望的类型从interface{}中获取值。

以下是代码的翻译:

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/mattn/go-scan"
  6. "log"
  7. )
  8. func main() {
  9. text := `["foo", 42]`
  10. var v interface{}
  11. err := json.Unmarshal([]byte(text), &v)
  12. if err != nil {
  13. log.Fatal(err)
  14. }
  15. var key string
  16. var val int
  17. e1, e2 := scan.ScanTree(v, "[0]", &key), scan.ScanTree(v, "[1]", &val)
  18. if e1 != nil || e2 != nil {
  19. log.Fatal(e1, e2)
  20. }
  21. fmt.Println(key, val)
  22. }

希望对你有帮助!

英文:

At the first, answer is No. But you can get values from interface{} with type you expected.
How about this?

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/mattn/go-scan"
  6. "log"
  7. )
  8. func main() {
  9. text := `["foo", 42]`
  10. var v interface{}
  11. err := json.Unmarshal([]byte(text), &v)
  12. if err != nil {
  13. log.Fatal(err)
  14. }
  15. var key string
  16. var val int
  17. e1, e2 := scan.ScanTree(v, "[0]", &key), scan.ScanTree(v, "[1]", &val)
  18. if e1 != nil || e2 != nil {
  19. log.Fatal(e1, e2)
  20. }
  21. fmt.Println(key, val)
  22. }

huangapple
  • 本文由 发表于 2015年1月23日 08:31:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/28101162.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定