Reputation: 9232
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
Reputation: 12403
Here are some comments on your code besides the conversion (which is also addressed at the end).
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