亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Go 錯誤:恐慌:運行時錯誤:無效的內存地址或零指針取消引用。

Go 錯誤:恐慌:運行時錯誤:無效的內存地址或零指針取消引用。

Go
侃侃無極 2023-06-05 09:16:37
我必須讓結構說 struct1 和 struct2,struct2 包含一個帶有 struct1 的映射,struct1 也包含一個映射,我想更改 struct1 中存在的映射。這是拋出運行時錯誤: 恐慌:運行時錯誤:無效內存地址或零指針取消引用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 回答

?
守著一只汪

TA貢獻1872條經驗 獲得超4個贊

您編寫的代碼在編譯時不會彈出 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,好吧,你告訴我什么是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)

}


查看完整回答
反對 回復 2023-06-05
  • 1 回答
  • 0 關注
  • 161 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號