Home > Software engineering >  Can't access map[string]*someStruct correctly
Can't access map[string]*someStruct correctly

Time:11-29

I'm trying to figure out how to access struct files of map the right way.

I have two structs

type ZipStructure struct {
    Pfx  []byte
    Cert []byte
    Key  []byte
    Json []byte
}
type ServerConfig struct {
    ClusterSetupZip  map[string]ZipStructure
}

I want to allocate space to the map and access the fields of ZipStructure.

For example, zs[DirName].Pfx = bytes

It's only possible if I change the declaration of the map to map[string]*ZipStructure

Although I'm getting an NRE

I was also trying to allocate space this way make(map[string]*ZipStructure, 4)` and it also didn't help.

CodePudding user response:

If you want to access the struct in the stored map, you can check if it exists or not, then create it:

if _, found := zs[DirName]; !found {
    zs[DirName] = &ZipStructure{
        //If you need, you can initialize the slices also here
        Pfx:  make([]byte,0),
        Cert: make([]byte,0),
        Key:  make([]byte,0),
        Json: make([]byte,0),
    }
}
//Now its accessible
zs[DirName].Pfx = append(zs[DirName].Pfx,b)
  •  Tags:  
  • go
  • Related