The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
yujianwjj

go 标准库 container/heap 的一个疑问

  •  
  •   yujianwjj · Mar 25, 2020 · 2349 views
    This topic created in 2258 days ago, the information mentioned may be changed or developed.

    container/heap 中的 Pop 方法,从堆当中移出一个元素,如果当前堆为空,那么调用 heap.Pop() 方法就会报错。

    panic: runtime error: index out of range [0] with length 0
    

    代码中确实没有对长度为 0 时的情况进行特殊处理。

    // Pop removes and returns the minimum element (according to Less) from the heap.
    // The complexity is O(log n) where n = h.Len().
    // Pop is equivalent to Remove(h, 0).
    func Pop(h Interface) interface{} {
    	n := h.Len() - 1
    	h.Swap(0, n)
    	down(h, 0, n)
    	return h.Pop()
    }
    

    我的疑问是为什么对这个情况不做处理?

    2 replies    2020-03-26 01:51:07 +08:00
    rrfeng
        1
    rrfeng  
       Mar 25, 2020
    容器有没有元素肯定要自己判断呀,不然给你返回啥?

    1. pop 返回 nil (???
    2. pop 返回元素+error (???
    你觉得哪种好?
    123444a
        2
    123444a  
       Mar 26, 2020 via Android
    楼主欢迎你加入中国人改造 go 社区,我们一起修改这个接口吧,返回值加入 error 即可,就为了跟英语世界不一样改它
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2602 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 42ms · UTC 05:23 · PVG 13:23 · LAX 22:23 · JFK 01:23
    ♥ Do have faith in what you're doing.