Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Decode Map Values Into Native Golang Structures

I personally think that Golang is a great development technology and one of the better that I’ve used. However, there is no such thing as a perfect development technology. That said, there are things to be desired in Golang out of the box. For example, I always find myself wishing that I could use type assertions to decode map values into a defined Go data structure.

Using a nifty package, this actually becomes a possibility and without much extra effort. We’re going to see how to take a map and convert it into a custom structure.

The example we explore won’t be particularly complex, but it will give you a good idea on what we’re after. Before we start coding, we need to obtain the Go dependency for decoding map values.

From the Command Prompt or Terminal, execute the following:

go get github.com/mitchellh/mapstructure

The mapstructure dependency by Mitchell Hashimoto does exactly what we’re looking for.

So how do we use this package? Create a new project and include the following Golang code. Don’t worry, we’ll break it down after.

package main

import (
    "fmt"
    "github.com/mitchellh/mapstructure"
)

type Person struct {
    Firstname string
    Lastname  string
    Address   struct {
        City  string
        State string
    }
}

func main() {
    mapPerson := make(map[string]interface{})
    var person Person
    mapPerson["firstname"] = "Nic"
    mapPerson["lastname"] = "Raboy"
    mapAddress := make(map[string]interface{})
    mapAddress["city"] = "San Francisco"
    mapAddress["state"] = "California"
    mapPerson["address"] = mapAddress
    mapstructure.Decode(mapPerson, &person)
    fmt.Println(person)
}

In the above example we have a custom data structure that will represent some personal information. This custom data structure also has a nested structure. We’re doing this to show extra complexity in what the package can accomplish.

In the main method we have two maps, one for the top level person information and one for the address information. After combining the two, we can decode it into our custom data structure and print it out.

Give it a spin and see how slick of a solution it is for your own project!

Nic Raboy

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in Java, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Apache Cordova. Nic writes about his development experiences related to making web and mobile development easier to understand.

Search

Follow Us

Subscribe

Subscribe to my newsletter for monthly tips and tricks on subjects such as mobile, web, and game development.

Subscribe on YouTube

Support This Site