1

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?

1
  • Your Result type is "unidiomatic" (an euphemism for "dead ugly"). Don't do such things. Redesign, refactor. Commented Aug 15, 2017 at 3:35

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

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.