DEV Community

Bryan Sazon
Bryan Sazon

Posted on

3

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)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay