运行时错误 : “assignment to entry in nil map”

标签 go

我是 go lang 的新手。我正在尝试读取 csv 文件并收集数据。

但是在运行之后我得到了这个错误:

panic: assignment to entry in nil map

goroutine 1 [running]:
panic(0x4dedc0, 0xc082002440)
        C:/Go/src/runtime/panic.go:464 +0x3f4
main.(*stateInformation).setColumns(0xc08202bd40, 0xc082060000, 0x11, 0x20)
        F:/Works/Go/src/examples/state-info/main.go:25 +0xda
main.main()
        F:/Works/Go/src/examples/state-info/main.go:69 +0xaea

我的代码:

package main

import (
    "encoding/csv"
    "fmt"
    "io"
    "log"
    "os"
    "strconv"
)

type stateInformation struct {
    columns map[string]int
}

type state struct {
    id               int
    name             string
    abbreviation     string
    censusRegionName string
}

func (info *stateInformation) setColumns(record []string) {
    for idx, column := range record {
        info.columns[column] = idx
    }
}

func (info *stateInformation) parseState(record []string) (*state, error) {
    column := info.columns["id"]
    id, err := strconv.Atoi(record[column])
    if err != nil {
        return nil, err
    }
    name := record[info.columns["name"]]
    abbreviation := record[info.columns["abbreviation"]]
    censusRegionName := record[info.columns["census_region_name"]]
    return &state{
        id:               id,
        name:             name,
        abbreviation:     abbreviation,
        censusRegionName: censusRegionName,
    }, nil
}

func main() {
    // #1 open a file
    f, err := os.Open("state_table.csv")
    if err != nil {
        log.Fatalln(err)
    }
    defer f.Close()

    stateLookup := map[string]*state{}

    info := &stateInformation{}

    // #2 parse a csv file
    csvReader := csv.NewReader(f)
    for rowCount := 0; ; rowCount++ {
        record, err := csvReader.Read()
        if err == io.EOF {
            break
        } else if err != nil {
            log.Fatalln(err)
        }

        if rowCount == 0 {
            info.setColumns(record)
        } else {
            state, err := info.parseState(record)
            if err != nil {
                log.Fatalln(err)
            }
            stateLookup[state.abbreviation] = state
        }
    }

    // state-information AL
    if len(os.Args) < 2 {
        log.Fatalln("expected state abbreviation")
    }
    abbreviation := os.Args[1]
    state, ok := stateLookup[abbreviation]
    if !ok {
        log.Fatalln("invalid state abbreviation")
    }

    fmt.Println(`
<html>
    <head></head>
    <body>
      <table>
        <tr>
          <th>Abbreviation</th>
          <th>Name</th>
        </tr>`)

    fmt.Println(`
        <tr>
          <td>` + state.abbreviation + `</td>
          <td>` + state.name + `</td>
        </tr>
    `)

    fmt.Println(`
      </table>
    </body>
</html>
    `)
}

我的代码有什么问题?

最佳答案

我不知道你想获得什么,但错误告诉你,columns 映射在赋值时没有 column 索引,对于这个原因引发了 panic 。

panic: assignment to entry in nil map

要使其正常工作,您必须在开始填充索引之前初始化 map 本身。

state := &stateInformation{
    columns: make(map[string]int),
}

或者另一种初始化方式:

func (info *stateInformation) setColumns(record []string) {
    info.columns = make(map[string]int)

    for idx, column := range record {
        info.columns[column] = idx
    }
}

关于运行时错误 : “assignment to entry in nil map” ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35986604/

相关文章:

xml - 在 Golang 中解码 XML 数组 : Only Getting The First Element

go - 从 slice 中删除选定元素的最佳方法

go - 你如何让 -tags netgo 成为 go 的默认值?

go - 无法将 StripPrefix 包装在另一个函数中(缺少 ServeHTTP 方法)

amazon-web-services - 将 Go 项目部署到 AWS Lambda 时出现 "PathError"

go - 在 Go 中取消阻塞操作

compiler-construction - 如何为 Go 构建 8g 和 6g Go 编译器

go - 如何在 Golang 中正确使用可变参数?

go - 用它的变量制作一个结构的 slice

Go结构标签抛出错误: "field tag must be a string"