Go 为什么我在函数中传递结构指针时总是得到nil字段值?
问题: 我有一个包含一个映射和两个切片的结构。当我传递指针值时,无论我做什么,结构中的这些集合总是nil(即,不能向映射或切片追加任何内容) 详细信息: 我不明白为什么会这样。我做了一个看似不相关的更改(我不记得了),现在结构中的映射没有附加任何内容。我将Map指针传递给后续函数,但它不断抛出错误“panic:assignment to entry in nil Map” 我传递了LinkResource和LinkReport类型值的指针,但它总是说映射为nil。作为调试测试,我甚至使用make(…)强制将LinkReport结构值归零,但当该值传递给后续函数时,它仍然声称映射和切片为零;这是怎么可能的?我该如何纠正它 链接资源Go 为什么我在函数中传递结构指针时总是得到nil字段值?,go,Go,问题: 我有一个包含一个映射和两个切片的结构。当我传递指针值时,无论我做什么,结构中的这些集合总是nil(即,不能向映射或切片追加任何内容) 详细信息: 我不明白为什么会这样。我做了一个看似不相关的更改(我不记得了),现在结构中的映射没有附加任何内容。我将Map指针传递给后续函数,但它不断抛出错误“panic:assignment to entry in nil Map” 我传递了LinkResource和LinkReport类型值的指针,但它总是说映射为nil。作为调试测试,我甚至使用make
package model
type LinkResource struct {
ID int
URL string
Health string
Status int
Message string
}
LinkReport
type LinkReport struct {
Summary map[string]int
BrokenLinks []LinkResource
UnsureLinks []LinkResource
}
抛出错误的逻辑
type LinkService struct { }
func (linkService *LinkService) populateLinkReportMetadata(responseCode int, message string, health string, link *model.LinkResource, linkReport *model.LinkReport) {
linkReport.Summary[health]++
link.Message = message
link.Health = health
link.Status = responseCode
switch health {
case constants.Broken:
linkReport.BrokenLinks = append(linkReport.BrokenLinks, *link)
break
case constants.Unsure:
linkReport.UnsureLinks = append(linkReport.UnsureLinks, *link)
break
}
}
测试函数以重现问题
func TestPopulateLinkReportMetadata(t *testing.T) {
link := model.LinkResource{}
linkReport := model.LinkReport{}
link.ID = 1234
link.URL = "http://someurl.com"
linkService := LinkService{}
t.Log("After analyzing a LinkResource")
{
linkService.populateLinkReportMetadata(http.StatusOK, link.Message, constants.Healthy, &link, &linkReport)
if linkReport.Summary[constants.Healthy] > 0 {
t.Logf("The LinkResource should be appended to the %s summary slice %s", constants.Healthy, checkMark)
} else {
t.Fatalf("The LinkResource should be appended to the %s summary slice %s", constants.Healthy, ballotX)
}
}
}
我很感激任何帮助,因为我很困惑,谢谢 下面是一个简单的错误示例:
type linkReport struct {
summary map[string]int
}
func main() {
var link linkReport
// panic: assignment to entry in nil map
link.summary["month"] = 12
}
还有一个简单的解决方案:
var link linkReport
link.summary = make(map[string]int)
link.summary["month"] = 12
或者您可以创建一个“新”功能:
func newLinkReport() linkReport {
return linkReport{
make(map[string]int),
}
}
func main() {
link := newLinkReport()
link.summary["month"] = 12
}
下面是一个简单的错误示例:
type linkReport struct {
summary map[string]int
}
func main() {
var link linkReport
// panic: assignment to entry in nil map
link.summary["month"] = 12
}
还有一个简单的解决方案:
var link linkReport
link.summary = make(map[string]int)
link.summary["month"] = 12
或者您可以创建一个“新”功能:
func newLinkReport() linkReport {
return linkReport{
make(map[string]int),
}
}
func main() {
link := newLinkReport()
link.summary["month"] = 12
}
谢谢@Steven Penny!谢谢@Steven Penny!