问题:我有一个结构,其中包含一个地图和两个切片。当我传递指针值时,无论我做什么,结构中的这些集合总是为零(即不能将任何内容附加到地图或切片)。详:我不明白为什么会发生这种情况。我做了一个看似无关的更改(我不记得了),现在没有任何东西会附加到结构中的地图上。我正在将Map指针传递给后续函数,但它不断抛出错误“panic:分配给nil map中的条目”。我传递了 LinkResource 和 LinkReport 类型值的指针,但它总是说映射为 nil。我甚至用make(...)强制将LinkReport结构值归零作为调试测试,但是当该值传递给后续函数时,它仍然声称Map和Slices为n;这怎么可能,我该如何纠正?友情链接资源package modeltype LinkResource struct { ID int URL string Health string Status int Message string}链接报告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) } }}我感谢任何帮助,因为我非常困惑,谢谢!
1 回答
扬帆大鱼
TA贡献1799条经验 获得超9个赞
下面是一个简单的错误示例:
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
}
- 1 回答
- 0 关注
- 82 浏览
添加回答
举报
0/150
提交
取消