简体   繁体   English

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

[英]How to create array of objects in golang?

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. 你正在打击类型系统,我会问你为什么要使用Go,如果你这样做的话。 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)
}

Perfect python syntax, but go unfortunately use something less readable. 完美的python语法,但遗憾的是使用不太可读的东西。 https://golang.org/ref/spec#Composite_literals https://golang.org/ref/spec#Composite_literals

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM