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

2020-03-25 11:00:36 +08:00
 yujianwjj

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

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

1804 次点击
所在节点    Go 编程语言
2 条回复
rrfeng
2020-03-25 11:12:57 +08:00
容器有没有元素肯定要自己判断呀,不然给你返回啥?

1. pop 返回 nil (???
2. pop 返回元素+error (???
你觉得哪种好?
123444a
2020-03-26 01:51:07 +08:00
楼主欢迎你加入中国人改造 go 社区,我们一起修改这个接口吧,返回值加入 error 即可,就为了跟英语世界不一样改它

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/655963

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX