duanhan1392 2017-01-27 17:15
浏览 49
已采纳

Golang柜台HTML标记的地图无法正常工作

I got a problem. I need to write a function to populate a mapping from element names—p, div, span, and so on — to the number of elements with that name in an HTML document tree. I made function outline2, it's not working, here is the eroor log:

html
panic: assignment to entry in nil map

    goroutine 1 [running]:
    panic(0x4c3b40, 0xc042010a90)
            F:/Go/src/runtime/panic.go:500 +0x1af
    main.outline2(0x0, 0xc0420320e0)
            F:/Go_Stuff/Books/Golang_stuff/exercises/src/gopl.io/ch5/outline/main.go:29 +0x1ae
    main.outline2(0x0, 0xc042032070)
            F:/Go_Stuff/Books/Golang_stuff/exercises/src/gopl.io/ch5/outline/main.go:34 +0xe3
    main.main()
            F:/Go_Stuff/Books/Golang_stuff/exercises/src/gopl.io/ch5/outline/main.go:23 +0x77

Here is the code:

func main() {
    doc, err := html.Parse(os.Stdin)
    if err != nil {
        fmt.Fprintf(os.Stderr, "outline: %v
", err)
        os.Exit(1)
    }
    outline2(nil, doc)
}
func outline2(tags map[string]int, n *html.Node) {
    fmt.Println(n.Data)
    if n.Type == html.ElementNode {
        fmt.Println(n.Data)
        tags[n.Data] += 1 // push tag
        fmt.Println(n.Data)

    }
    for c := n.FirstChild; c != nil; c = c.NextSibling {
        outline2(tags, c)


    }
}

Please, point out my mistakes. I don't know what to do =(

  • 写回答

1条回答 默认 最新

  • dua55014 2017-01-27 17:33
    关注

    Error is exact. You can't assign in nil map. You must first allocate. Also you need something to work, you func return nothing. So

    outline := make(map[string]int) //allocate and name your map
    outline2(outline, doc)
    fmt.Println(outline) //do something with it
    

    should work

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题