错误:紧急:运行时错误:无效的内存地址或nil指针取消引用。在另一个结构中存在的结构中更改映射,

时间:2019-01-29 07:35:56

标签: go

我不得不说struct1和struct2,struct2包含一个带有struct1的映射,struct1也包含一个映射,我想更改struct1中存在的映射。

这将引发运行时错误: 紧急:运行时错误:无效的内存地址或nil指针取消引用

type FailureData struct {
    failuresInCommits map[string][]string 
}

type DetectionResults struct {
    Failures map[git_repo.FilePath]*FailureData
        //Have other things
}

func (r *DetectionResults) Fail(filePath git_repo.FilePath, message 
           string, commits []string) {  
        ok := r.Failures[filePath].failuresInCommits //error occurs here    
        if r.Failures[filePath].failuresInCommits == nil {       
            r.Failures[filePath].failuresInCommits = make(map[string][]string)
        }
        if len(ok) == 0 {
            r.Failures[filePath].failuresInCommits[message] = commits
        } else {
            r.Failures[filePath].failuresInCommits[message] = 
               append(r.Failures[filePath].failuresInCommits[message], 
                      commits...)   
        }
}

1 个答案:

答案 0 :(得分:0)

您编写的代码在编译时不会弹出nil错误,仅当您以错误的方式使用它时才会导致nil点错误。

failuresInCommits map[string][]string是在make()之后使用吗?

Failures map[git_repo.FilePath]*FailureData是在'make()'之后使用的吗?

好,现在您专注于 ok := r.Failures[filePath].failuresInCommits,是否确定r.Failures[filePath]返回'failuresIncommits,true',

如果没有,那么r.Failures [filePath]为零,好吧,你告诉我什么是nil.failuresInCommits

还有一个风险,就是您只能在此特定程序包中进行x.failureInCommits。如果您在其他软件包中执行相同的操作,则由于字段大小写受限,将无法访问x.failureInCommits。

如何制作?

package main

type FilePath string

type FailureData struct {
    failuresInCommits map[string][]string
}

func NewFailureData() FailureData {
    return FailureData{
        failuresInCommits: make(map[string][]string, 0),
    }
}
func (fd *FailureData) Set(k string, v []string) {
    fd.failuresInCommits[k] = v
}

type DetectionResults struct {
    Failures map[FilePath]*FailureData
    //Have other things
}

func NewDetectionResults() *DetectionResults {
    return &DetectionResults{
        Failures: make(map[FilePath]*FailureData, 0),
    }
}
func (dr *DetectionResults) Set(fp FilePath, fd *FailureData) {
    dr.Failures[fp] = fd
}

func main() {
    fd := NewFailureData()
    dr := NewDetectionResults()
    comments := []string{"push error", "commit error", "add error"}

    fd.Set("hash-18ef8abujce8fad0h8j", comments)
    dr.Set("/etc/go/gopath/src/github.com/xxx/xxx/main.go: 12", &fd)
}