Skip to content

Instantly share code, notes, and snippets.

@manjeettahkur
Created May 30, 2022 13:00
Show Gist options
  • Save manjeettahkur/7315581185d226ef35d565d8ab8c3da2 to your computer and use it in GitHub Desktop.
Save manjeettahkur/7315581185d226ef35d565d8ab8c3da2 to your computer and use it in GitHub Desktop.
convert map to struct in go programming language
package main
import (
"fmt"
"reflect"
)
func main() {
source := map[string]any{
"A": 23,
"B": "Hello",
}
type T struct {
B string
A int
}
target := new(T)
s := reflect.ValueOf(target).Elem()
typeOfT := s.Type()
for i := 0; i < s.NumField(); i++ {
f := s.Field(i)
fv := source[typeOfT.Field(i).Name]
f.Set(reflect.ValueOf(fv))
}
fmt.Printf("%+v\n", target)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment