How to create array of objects in golang?

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-03 07:27:26

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)
}

Perfect python syntax, but go unfortunately use something less readable. https://golang.org/ref/spec#Composite_literals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!