登录
首页 >  Golang >  Go问答

Go Runtime 错误:“在 nil 映射中输入的信号”

来源:Golang技术栈

时间:2023-04-11 10:38:34 480浏览 收藏

大家好,今天本人给大家带来文章《Go Runtime 错误:“在 nil 映射中输入的信号”》,文中内容主要涉及到golang,如果你对Golang方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!

问题内容

我是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) 
    
    
      
`) fmt.Println(` `) fmt.Println(`
Abbreviation Name
` + state.abbreviation + ` ` + state.name + `
声明:本文转载于:Golang技术栈 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>