将`map[string]*[]interface{}`转换为其他类型的切片或数组。

huangapple go评论76阅读模式
英文:

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

问题

我有以下代码:

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

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

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

之后,我想从这个map中获取users并将其转换为*[]models.User类型。但是我很难找到正确的方法来实现这一点。我想要做以下操作,但显然行不通:

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

你有什么办法可以解决这个问题吗?

英文:

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

得分: 2

除了转换(也在最后进行了处理)之外,以下是对你的代码的一些评论。

  • 在这种情况下,没有真正需要使用切片的指针,因为切片只是指向底层数组的头部值。因此,切片值可以作为对底层数组的引用工作。
  • 由于interface{}变量可以引用任何类型的值(包括切片),在Result中不需要使用interface{}的切片,可以将其定义为type Results map[string]interface{}

说了这些,这是修改后的代码:

var users []User
users = getUsers()

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

fmt.Println(results)

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

fmt.Println(userResults)

你可以在这个playground中找到完整的代码:

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

英文:

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

huangapple
  • 本文由 发表于 2017年8月15日 09:43:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/45685383.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定