如何在golang中创建对象数组? [英] How to create array of objects in golang?
问题描述
我有一个需要将对象数组存储在一个变量中的需求。这些对象是不同类型的。请参阅以下示例:
v:= [{name:ravi},
[art ,编码,音乐,旅行],
{language:golang},
{experience:no}
]
注意第二个元素是字符串本身的数组。经过研究,我想将它存储为如下接口类型:
var v interface {} = [{name: ravi},
[art,coding,music,travel],
{language:golang},
{experience没有}
]
但是,我收到了一些我无法编译的错误找出答案。
您可能要求的是 playground link : b
导入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。考虑利用类型系统 - 游乐场链接:
包主要
导入fmt
类型候选结构{
名称字符串
兴趣[] string
language string
experience bool
}
func main(){
candidates:= [] candidate {
{
名称:ravi,
兴趣:[] string {art,coding,music,travel},
语言:golang,
经验:假,
},
}
fmt.Println(候选人)
}
I have a requirement in which I need to store array of objects in a variable. The objects are of different types. Refer to following example:
v := [ {"name":"ravi"},
["art","coding","music","travel"],
{"language":"golang"},
{"experience":"no"}
]
Notice the second element is array of string itself. After research, I thought of storing this as interface type like:
var v interface{} = [ {"name":"ravi"},
["art","coding","music","travel"],
{"language":"golang"},
{"experience":"no"}
]
Still, I am getting few compilation errors which I am not able to find out.
What you're asking for is possible -- 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)
}
But you probably don't want to be doing this. You're fighting the type system, I would question why you're using Go if you were doing it like this. Consider leveraging the type system -- playground link:
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)
}
这篇关于如何在golang中创建对象数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!