英文:
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 ofinterface{}
inResult
, you can just define it astype 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:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论