我有一个需要将对象数组存储在变量中的要求。对象是不同类型的。请参考以下示例:
v := [ {"name":"ravi"}, ["art","coding","music","travel"], {"language":"golang"}, {"experience":"no"} ]
注意第二个元素是字符串本身的数组。经过研究,我想将其存储为以下接口类型:
var v interface{} = [ {"name":"ravi"}, ["art","coding","music","travel"], {"language":"golang"}, {"experience":"no"} ]
尽管如此,我还是遇到了一些无法找到的编译错误。
您要的是可能的- 游乐场链接:
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) }
但是您可能不想这样做。您正在与类型系统进行斗争,如果您这样做,我会质疑您为什么要使用Go。考虑利用类型系统- 游乐场链接:
package main import "fmt" type candidate struct { name string interests []string language string experience bool } func main() { candidates := []candidate{ { name: "ravi", interests: []string{"art", "coding", "music", "travel"}, language: "golang", experience: false, }, } fmt.Println(candidates) }