Created
May 30, 2022 13:00
-
-
Save manjeettahkur/7315581185d226ef35d565d8ab8c3da2 to your computer and use it in GitHub Desktop.
convert map to struct in go programming language
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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