duansha8115 2016-03-14 11:42
浏览 92
已采纳

运行时错误:“分配给nil映射中的条目”

I'm new in go lang. I'm trying to read csv file and collecting data.

But after run it I got this error :

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

My code :

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>
    `)
}

What's wrong in my code?

  • 写回答

1条回答 默认 最新

  • duanmeng3573 2016-03-14 12:00
    关注

    I don't know what you are trying to obtain, but the error tells, that columns map does not have a column index on the moment of assignment and for this reason is throwing a panic.

    panic: assignment to entry in nil map
    

    To make it work you have to initialize the map itself before to start to populate with indexes.

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

    Or another way to initialize:

    func (info *stateInformation) setColumns(record []string) {
        info.columns = make(map[string]int)
    
        for idx, column := range record {
            info.columns[column] = idx
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 echarts动画效果失效的问题。官网下载的例子。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加