如何在golang中创建对象数组?

时间:2015-10-09 06:29:37

标签: arrays go variable-assignment

我有一个要求,我需要在变量中存储对象数组。对象是不同类型的。请参阅以下示例:

 v := [ {"name":"ravi"},
        ["art","coding","music","travel"],
        {"language":"golang"},
        {"experience":"no"}
      ]

注意第二个元素是字符串本身的数组。经过研究,我想把它存储为接口类型,如:

 var v interface{} = [ {"name":"ravi"},
                       ["art","coding","music","travel"],
                       {"language":"golang"},
                       {"experience":"no"}
                     ]

但是,我收到的编译错误很少,我无法找到。

2 个答案:

答案 0 :(得分:14)

你可能要求的是什么 - playground link

#info in the file
[System]
serial=130204
[Summary]
file_created=2014-11-20 03:02:09
user=j
....#more info
[date]#after this key starts the keys
...
[AX1]
units=m/s
serial_setting=38400
height=70.4
stats=avg
formula=yes
site=site1
[H4]
serial_setting=38100
height=20.6
stats=std
formula=yes
site=site2
[V3]
units=m
...

但你可能不想这样做。你正在打击类型系统,我会问你为什么要使用Go,如果你这样做的话。考虑利用类型系统 - playground link

package main

import "fmt"

func main() {
    v := []interface{}{
        map[string]string{"name": "ravi"},
        []string{"art", "coding", "music", "travel"},
        map[string]string{"language": "golang"},
        map[string]string{"experience": "no"},
    }
    fmt.Println(v)
}

答案 1 :(得分:-4)

完美的python语法,但遗憾的是使用不太可读的东西。 https://golang.org/ref/spec#Composite_literals