duandao3265 2017-04-12 21:15
浏览 275
已采纳

在Golang中制作哈希数组

I'm brand new to Go and having some trouble with nested data structures. Below is a array of hashes I mocked up that I need to make in Golang. I'm just confused with the whole having to declare the variable type beforehand and whatnot. Any ideas?

 var Array = [
   {name: 'Tom', dates: [20170522, 20170622], images: {profile: 'assets/tom-profile', full: 'assets/tom-full'}},
   {name: 'Pat', dates: [20170515, 20170520], images: {profile: 'assets/pat-profile', full: 'assets/pat-full'}} 
    ...,
    ... ]
  • 写回答

2条回答 默认 最新

  • douba05167 2017-04-12 21:38
    关注

    What is called a 'hash' in Ruby is called a 'map' (translating keys to values) in Go.

    However, Go is a statically typechecked language. A map can only map a certain type to another type, e.g. a map[string]int maps string values to integeger. That is not what you want here.

    So what you want is a struct. Indeed, you need to define the type beforehand. So what you would do:

    // declaring a separate 'Date' type that you may or may not want to encode as int. 
    type Date int 
    type User struct {
        Name string
        Dates []Date
        Images map[string]string
    }
    

    Now that this type is defined, you can use it in another type:

    ar := []User{
      User{
        Name: "Tom",
        Dates: []Date{20170522, 20170622},
        Images: map[string]string{"profile":"assets/tom-profile", "full": "assets/tom-full"},
      },
      User{
        Name: "Pat",
        Dates: []Date{20170515, 20170520},
        Images: map[string]string{"profile":"assets/pat-profile", "full": "assets/pat-full"},
      },
    }   
    

    Note how we are defining User as a struct, but images as a map of string to image. You could also define a separate Image type:

    type Image struct {
      Type string // e.g. "profile"
      Path string // e.g. "assets/tom-profile"
    }
    

    You would then not define Images as map[string]string but as []Image, that is, slice of Image structs. Which one is more appropriate depends on the use case.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行