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条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?