本文介绍了在Golang中制作哈希数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Go语言的新手,并且在嵌套数据结构方面遇到了一些麻烦.以下是我需要在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'}} 
    ...,
    ... ]

推荐答案

在Ruby中所谓的哈希"在Go中称为映射"(将键转换为值).

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

但是,Go是静态进行类型检查的语言.映射只能将某种类型映射到另一种类型,例如map [string] int将字符串值映射到整数.那不是你想要的.

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

请注意我们如何将User定义为结构,而将images定义为字符串到图像的映射.您还可以定义单独的图片类型:

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

然后,您将不将Images定义为map[string]string,而是定义为[]Image,即Image结构的切片.哪一种更合适取决于使用情况.

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.

这篇关于在Golang中制作哈希数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 03:20