无法正确访问 map[string]*someStruct。

huangapple go评论77阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2021年11月28日 19:48:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/70143095.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定