Search code examples
gostructcomposite-literals

Properly initialize a map[string]interface struct


I have the following struct:

type InstructionSet struct {
    Inst map[string]interface{}
}

In the Inst map I'd like to put something like

Inst["cmd"] = "dir"
Inst["timeout"] = 10

Now I'd like to initialize it directly from code, but I'm not finding the proper way to do it

    info := InstructionSet{
        Inst: {
            "command": "dir",
            "timeout": 10,
            },
    }

In this way I get an error saying missing type in composite literal. I tried few variations, but I can't get the proper way.


Solution

  • The error says the type is missing in the composite literal, so do provide the type:

    info := InstructionSet{
        Inst: map[string]interface{}{
            "command": "dir",
            "timeout": 10,
        },
    }
    

    Try it on the Go Playground.