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'}}
...,
... ]
You don't need to declare the variable type beforehand, at least not in this simple example, although you need to "mention" your types when initializing your values with composite literals.
For example this
[{}]
(array of objects?) makes no sense to the Go compiler, instead you need to write something like this[]map[string]interface{}{}
(slice of maps whose keys are strings and whose values can have any type)To break it down:
[]
- slice of whatever type comes after itmap
- builtin map (think hash)[string]
- inside the square brackets is the type of the map key, can be almost any typeinterface{}
- the type of the map values{}
- this initializes/allocate the whole thingSo your example in Go would look something like this:
Read more on maps and what key types you can use here: https://golang.org/ref/spec#Map_types
That said, in Go, most of the time, you would first define your structured types more concretely and then use them instead of maps, so something like this makes more sense in Go:
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:
Now that this type is defined, you can use it in another type:
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:
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.