TheJediCowboy
TheJediCowboy

Reputation: 9232

Golang convert map[string]*[]interface{} to slice or array of other type

I have the following

type Results map[string]*[]interface{}

var users *[]models.User
users = getUsers(...)

results := Results{}
results["users"] = users

Later, id like to be able to grab users from this map and cast it to *[]models.User

I am having a hard time figuring out the right way to do this. Id like to do the following, but it obviously does not work.

var userResults *[]models.User
userResults = (*results["users").(*[]models.User)

Any idea on how to do this?

Upvotes: 1

Views: 4708

Answers (1)

eugenioy
eugenioy

Reputation: 12403

Here are some comments on your code besides the conversion (which is also addressed at the end).

  • There is no real need of using a pointer to a slice in this case, since slices are just header values pointing to the underlying array. So slice values would work as references to the underlying array.
  • Since an interface{} variable can reference values of any kind (including slices), there is no need to use a slice of interface{} in Result, you can just define it as type Results map[string]interface{}.

Having said this, here's how the modified code would look like:

var users []User
users = getUsers()

results := Results{}
results["users"] = users

fmt.Println(results)

var userResults []User
userResults = results["users"].([]User)

fmt.Println(userResults)

You can find the complete code in this playground:

https://play.golang.org/p/zL4IkWy97j

Upvotes: 3

Related Questions