doujiao8649 2019-03-25 16:13
浏览 30
已采纳

如何执行结构的方法,该结构是其他结构的字段

I created such 2 structs:

type HostsFile struct {
    path    string
    masters string
    nodes   string
}

type AnsInstance struct {
    name      string
    url       string
    yamlPath  string
    user      string
    pass      string
    branch    string
    hostsFile *HostsFile
}

HostsFile struct have such methods:

func (p *HostsFile) SetMasters(masters string) {
    p.masters = masters
}

func (p *HostsFile) SetNodes(nodes string) {
    p.nodes = nodes
}

and AnsInstance has such one which is using methods from HostFile struct:

func (p *AnsInstance) PrepInstExec(masters string, nodes string) {
    p.hostsFile.SetMasters(masters)
    p.hostsFile.SetNodes(nodes)
    p.hostsFile.GenerateHostsFile()
}

When im executing PrepInstExec in such way:

ansInstance.PrepInstExec("lalala,fafafaf", "bakuka,matata")

Im getting error:

panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x18 pc=0x4ccba3]

goroutine 1 [running]:
card-installer/ansexec.(*HostsFile).SetMasters(...)
        /home/holo/go/src/card-installer/ansexec/ansexec.go:19
card-installer/ansexec.(*AnsInstance).PrepInstExec(0xc0000c5e90, 0x6d1a2c, 0xe, 0x6d15b9, 0xd)
        /home/holo/go/src/card-installer/ansexec/ansexec.go:145 +0x53
main.main()
        /home/holo/go/src/card-installer/main.go:101 +0x84e
exit status 2

What am i doing wrong? Is there posibility to exec methods of one struct which is embedded to other?

EDIT:

I am creating new AnsInstance in such way:

func NewAnsInstance(name string, url string, path string) *AnsInstance {
    p := new(AnsInstance)
    p.name = name
    p.url = url
    p.yamlPath = path
    p.branch = "master"
    return p
}
  • 写回答

2条回答 默认 最新

  • dongwu1410 2019-03-25 16:28
    关注

    Since hostsFile *HostsFile is of type pointer, the default/zero value while creating an instance of the struct will be nil. So calling methods on nil will panic.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路