2017-04-12 82 views
1

我是Go的全新产品,在嵌套数据结构方面遇到了一些麻烦。下面是我嘲笑我需要在Golang制作的一系列哈希。我只是混淆整体必须事先声明变量类型和whatnot。有任何想法吗?在Golang中制作哈希阵列

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'}} 
    ..., 
    ... ] 
+0

'type Row struct {name string ....}'--- start带着某些东西,并在有特定问题时返回。 – zerkms

回答

1

Ruby中所谓的'散列'在Go中被称为'映射'(将键转换为值)。但是,Go是statically typechecked language。地图只能将某种类型映射到另一种类型,例如一个map [string] int将字符串值映射到integeger。这不是你想要的。

所以你想要的是一个结构。事实上,您需要事先定义类型。所以,你会做什么:

// 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 
} 

现在,这种类型的定义,你可以在其他类型的使用它:

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"}, 
    }, 
} 

注意我们是如何定义用户的结构,但图像的地图字符串图像。你也可以定义一个单独的图像类型:

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

那么你就不会定义图片作为map[string]string[]Image,即图像结构的片。哪一个更合适取决于用例。

+0

这很棒!我确实有几个问题,日期和用户之前的空括号的目的是什么?你能解释什么类型的结构?为Image创建一个结构而不仅仅是一个地图有什么好处? –

1

尽管在初始化复合文字时需要“提及”您的类型,但您不需要事先声明变量类型,至少不要在此简单示例中声明变量类型。例如[{}](对象数组?)是没有意义的围棋编译器,而不是你需要写这样的事情[]map[string]interface{}{}(地图切片,它的键是字符串,其值可以是任何类型)

进行分解:

  1. [] - 无论何种类型片来后
  2. map - 内置的地图(哈希认为)
  3. [string] - 方括号中是地图密钥类型, 可以几乎任何类型的
  4. interface{} - 地图的类型值
  5. {} - 这个初始化/分配整个事情

所以在进入你的例子会是这个样子:

var Array = []map[string]interface{}{ 
    {"name":"Tom", "dates": []int{20170522, 20170622}, "images": map[string]string{"profile": "assets/tom-profile", "full": "assets/tom-full"}}, 
    {"name":"Pat", "dates": []int{20170515, 20170520}, "images": map[string]string{"profile": "assets/pat-profile", "full": "assets/pat-full"}}, 
    // ... 
} 

阅读更多地图和你可以在这里使用的关键类型:https://golang.org/ref/spec#Map_types

这就是说,在Go中,大部分时间,你会首先更具体地定义你的结构化类型,然后用它们代替地图,所以像这样的东西在Go中更有意义:

type User struct { 
    Name string 
    Dates []int 
    Images Images 
} 

type Images struct { 
    Profile string 
    Full string 
} 

var Array = []User{ 
    {Name:"Tom", Dates:[]int{20170522, 20170622}, Images:Images{Profile:"assets/tom-profile", Full:"assets/tom-full"}}, 
    {Name:"Pat", Dates:[]int{20170515, 20170520}, Images:Images{Profile:"assets/pat-profile", Full:"assets/pat-full"}}, 
}