DEV Community

Bryan Sazon
Bryan Sazon

Posted on

Go - Convert Structs to Map

#go

This hack uses https://github.com/fatih/structs

package main

import (
    "fmt"

    "github.com/fatih/structs"
)

type User struct {
    FirstName string `structs:"first_name"`
    LastName  string `structs:"last_name"`
}

func main() {
    a := User{FirstName: "John", LastName: "Wick"}
    s := structs.New(a)
    m := s.Map()
    for k, v := range m {
        fmt.Println("key", k, "value", v)
    }
}

Output is:

key first_name value John
key last_name value Wick

Top comments (0)