How to create array of objects in golang?

前端 未结 2 441
有刺的猬
有刺的猬 2021-02-04 08:31

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\":\         


        
相关标签:
2条回答
  • 2021-02-04 09:05

    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)
    }
    
    0 讨论(0)
  • 2021-02-04 09:17

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

    0 讨论(0)
提交回复
热议问题