英文:
Can't access map[string]*someStruct correctly
问题
我正在尝试弄清楚如何正确访问映射的结构文件。
我有两个结构体:
type ZipStructure struct {
    Pfx  []byte
    Cert []byte
    Key  []byte
    Json []byte
}
type ServerConfig struct {
    ClusterSetupZip  map[string]ZipStructure
}
我想为映射分配空间并访问ZipStructure的字段。
例如,zs[DirName].Pfx = bytes
只有当我将map的声明更改为map[string]*ZipStructure时才可能实现。
尽管我遇到了一个NRE错误。
我还尝试以这种方式分配空间make(map[string]*ZipStructure, 4),但也没有帮助。
英文:
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.
答案1
得分: 1
如果你想访问存储的映射中的结构体,你可以检查它是否存在,然后创建它:
if _, found := zs[DirName]; !found {
    zs[DirName] = &ZipStructure{
        //如果需要,你也可以在这里初始化切片
        Pfx:  make([]byte,0),
        Cert: make([]byte,0),
        Key:  make([]byte,0),
        Json: make([]byte,0),
    }
}
//现在可以访问了
zs[DirName].Pfx = append(zs[DirName].Pfx,b)
英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论