Go - Convert Structs to Map
Bryan Sazon
Posted on April 26, 2020
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
💖 💪 🙅 🚩
Bryan Sazon
Posted on April 26, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.