V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
yujianwjj
V2EX  ›  Go 编程语言

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

  •  
  •   yujianwjj · 2020-03-25 11:00:36 +08:00 · 1791 次点击
    这是一个创建于 1465 天前的主题,其中的信息可能已经有所发展或是发生改变。

    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 条回复    2020-03-26 01:51:07 +08:00
    rrfeng
        1
    rrfeng  
       2020-03-25 11:12:57 +08:00
    容器有没有元素肯定要自己判断呀,不然给你返回啥?

    1. pop 返回 nil (???
    2. pop 返回元素+error (???
    你觉得哪种好?
    123444a
        2
    123444a  
       2020-03-26 01:51:07 +08:00 via Android
    楼主欢迎你加入中国人改造 go 社区,我们一起修改这个接口吧,返回值加入 error 即可,就为了跟英语世界不一样改它
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4958 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 09:38 · PVG 17:38 · LAX 02:38 · JFK 05:38
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.