doujingtang6580 2017-08-15 01:43
浏览 1870

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

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条回答 默认 最新

  • dtrb96410 2017-08-15 02:10
    关注

    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

    评论

报告相同问题?

悬赏问题

  • ¥15 luckysheet
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误