WTF are we even talking about???
Well, we can create struct types (NOTE: types, not just variables😒) dynamically, based on the keys and the types of each individual value in a given hashmap... Yes!!!
Dynamically! During runtime!! From a Hashmap!!! A new struct type!!!! And use it of'course😃
Here is full code with the relevant method (mapToStruct
), and usage example:
package main
import (
"fmt"
"reflect"
"strings"
)
func mapToStruct(m map[string]interface{}) reflect.Value {
var structFields []reflect.StructField
for k, v := range m {
sf := reflect.StructField{
Name: strings.Title(k),
Type: reflect.TypeOf(v),
}
structFields = append(structFields, sf)
}
// Creates the struct type
structType := reflect.StructOf(structFields)
// Creates a new struct
return reflect.New(structType)
}
func verifyStructFields(sr reflect.Value){
fmt.Println("\n---Fields found in struct..")
val := reflect.ValueOf(sr.Interface()).Elem()
for i := 0; i < val.NumField(); i++ {
fmt.Println(val.Type().Field(i).Name)
}
}
func setStructValues(sr reflect.Value){
fmt.Println("\n---Setting struct fields...")
sr.Elem().FieldByName("Name").SetString("Joe")
sr.Elem().FieldByName("Surname").SetString("Biden")
sr.Elem().FieldByName("Age").SetInt(79)
}
func main() {
m := make(map[string]interface{})
m["name"] = "Donald"
m["surname"] = "Trump"
m["age"] = 72
sr := mapToStruct(m)
fmt.Println("\n---Created type:", reflect.ValueOf(sr).Kind())
verifyStructFields(sr)
setStructValues(sr)
fmt.Printf("\n---Dynamically created and initialized struct:\n%#v", sr)
}
Cool, ain't it🥶
Top comments (0)