dpwbc42604 2011-07-05 11:00
浏览 8
已采纳

Golang帮助反思以获取价值

I'm very new in Go. I was wondering how do I get value of mappings out of this using Reflection in Go.


type url_mappings struct{
    mappings map[string]string
}

func init() {
    var url url_mappings
    url.mappings = map[string]string{
        "url": "/",
        "controller": "hello"}

Thanks

  • 写回答

1条回答 默认 最新

  • dongpanshi2839 2011-07-05 11:26
    关注
    import "reflect"
    v := reflect.ValueOf(url)
    f0 := v.Field(0) // Can be replaced with v.FieldByName("mappings")
    mappings := f0.Interface()
    

    mappings's type is interface{}, so you can't use it as a map. To have the real mappings that it's type is map[string]string, you'll need to use some type assertion:

    realMappings := mappings.(map[string]string)
    println(realMappings["url"])
    

    Because of the repeating map[string]string, I would:

    type mappings map[string]string
    

    And then you can:

    type url_mappings struct{
        mappings // Same as: mappings mappings
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器