英文:
How to create array of objects in golang?
问题
我有一个需求,需要将对象数组存储在一个变量中。这些对象的类型各不相同。请参考以下示例:
v := [ {"name":"ravi"},
["art","coding","music","travel"],
{"language":"golang"},
{"experience":"no"}
]
请注意,第二个元素本身是一个字符串数组。经过研究,我考虑将其存储为接口类型,如下所示:
var v interface{} = [ {"name":"ravi"},
["art","coding","music","travel"],
{"language":"golang"},
{"experience":"no"}
]
然而,我遇到了一些编译错误,我找不出原因。
英文:
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.
答案1
得分: 34
你要求的是可能的 - playground链接:
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。考虑利用类型系统 - playground链接:
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)
}
英文:
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)
}
答案2
得分: -5
完美的Python语法,但不幸的是Go使用了一些不太易读的东西。
https://golang.org/ref/spec#Composite_literals
英文:
Perfect python syntax, but go unfortunately use something less readable.
https://golang.org/ref/spec#Composite_literals
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论