带结构的字符串Golang切片[已关闭]

ykejflvf  于 2023-01-15  发布在  Go
关注(0)|答案(1)|浏览(123)

编辑问题以包含desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将有助于其他人回答问题。
昨天关门了。
Improve this question
我正在尝试构建一个string(key)切片,其值为struct。IDE没有给我错误消息,但当我尝试向切片添加项时,Go将返回以下错误:
对nilMap表项的赋值
有谁知道我该怎么做吗?

type CrawlerChanges struct {
    Id        int       `gorm:"AUTO_INCREMENT"`
    CompanyId int       `gorm:"AUTO_INCREMENT"`
    Page      string    `gorm:"AUTO_INCREMENT" json:"page"`
    Changes   string    `gorm:"not null" json:"changes"`
    CreatedAt time.Time `gorm:"DEFAULT:current_timestamp" json:"createdAt"`
    UpdatedAt time.Time `gorm:"DEFAULT:null" json:"updatedAt"`
    DeletedAt time.Time `gorm:"DEFAULT:null" json:"deletedAt"`
}

type Changes struct {
    Dates map[string][]models.CrawlerChanges `json:"dates"`
}

for i, _ := range changes {
    y := strconv.Itoa(changes[i].CreatedAt.Year())
    m := changes[i].CreatedAt.Month().String()
    d := strconv.Itoa(changes[i].CreatedAt.Day())

    c.Dates[y+m+d] = append(c.Dates[y+m+d], models.CrawlerChanges{
        Id:        changes[i].Id,
        CompanyId: changes[i].CompanyId,
        Page:      changes[i].Page,
        Changes:   changes[i].Changes,
        CreatedAt: changes[i].CreatedAt,
    })
}

我明白我试图附加到(我认为)不存在的东西上,但是在附加之前"创建"它的诀窍是什么?

kknvjkwl

kknvjkwl1#

看起来您的c.Dates是一张Map。
你在初始化它之前给它赋值。
所以在赋值之前先初始化这个Map。
例如,c.Dates = make(map[string]models.CrawlerChanges, 0)

相关问题