在 Golang 中制作哈希数组
时间:2023-04-06
浏览:342
作者:佚名
哈喽!大家好,很高兴又见面了,我是golang学习网的一名作者,今天由我给大家带来一篇《在 Golang 中制作哈希数组》,本文主要会讲到golang等等知识点,希望大家一起学习进步,也欢迎大家关注、点赞、收藏、转发! 下面就一起来看看吧!
问题内容
我是 Go 新手,在嵌套数据结构方面遇到了一些麻烦。下面是我模拟的一组哈希,我需要在 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'}}
...,
... ]
正确答案
在 Ruby 中所谓的“哈希”在 Go 中称为“映射”(将键转换为值)。
然而,Go 是一种[静态类型检查的语言](https://stackoverflow.com/questions/1517582/what-is-the- difference-between-statically-typed-and-dynamically-typed- languages)。映射只能将某种类型映射到另一种类型,例如 map[string]int 将字符串值映射到整数。这不是你想要的。
所以你想要的是一个结构。实际上,您需要事先定义类型。所以你会做什么:
// 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"},
},
}
请注意我们如何将 User 定义为结构体,而将图像定义为字符串到图像的映射。您还可以定义一个单独的 Image 类型:
type Image struct {
Type string // e.g. "profile"
Path string // e.g. "assets/tom-profile"
}
然后,您不会将 Images 定义为,map[string]string而是定义为[]Image,即 Image 结构的切片。哪个更合适取决于用例。
今天关于《在 Golang 中制作哈希数组》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于golang的内容请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
