DEV Community

Nitin Bansal
Nitin Bansal

Posted on

Creating a struct type dynamically at runtime using a Hashmap!!!😳

#go

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)
}
Enter fullscreen mode Exit fullscreen mode

Cool, ain't it🥶

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

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

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

Okay