Decode Map Values Into Native Golang Structures

Datetime:2017-04-18 06:11:47         Topic: Golang          Share        Original >>
Here to See The Original Article!!!

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:

goget 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
        Statestring
    }
}
 
func main() {
    mapPerson := make(map[string]interface{})
    var personPerson
    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!








New