24

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.

2
  • You have to define your data structures Commented Oct 9, 2015 at 6:48
  • 3
    Can someone point out the reasons for down votes, so that I can put my questions in a better way next time. Commented Oct 13, 2015 at 6:11

2 Answers 2

36

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)
}
Sign up to request clarification or add additional context in comments.

1 Comment

"I would question why you're using Go if you were doing it like this". They need to represent this data structure. You would advise using a different programming language if they have to work with data structures that are like that? Weird advise.
-6

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.