go - Container/heap Pop() on empty heap -


i have used container/heap package implement priority queue. 1 thing bothers me though. should behaviour of interface.pop() method if heap empty? don't see mentioned in documentation , source code doesn't seem expecting situation:

// pop removes minimum element (according less) heap // , returns it. complexity o(log(n)) n = h.len(). // equivalent remove(h, 0). // func pop(h interface) interface{} {         n := h.len() - 1         h.swap(0, n)         down(h, 0, n)         return h.pop() } 

clearly, if h.len() 0 not going work well. meant panic or user expected check whether there items left?

the natural behaviour panic. intheap example does.

as pointed out in comments, control not reach h.pop() if h.swap() panics. however, h.pop() can still called on empty heap if heap.remove() given -1 index:

// remove removes element @ index heap. // complexity o(log(n)) n = h.len(). // func remove(h interface, int) interface{} {     n := h.len() - 1     if n != {         h.swap(i, n)         down(h, i, n)         up(h, i)     }     return h.pop() } 

if h.swap() panics on negative indices, h.pop() should panic consistency.

having h.swap() silently ignore negative indices , h.pop() return default value nil consistent, other programmers find surprising don't recommend it.


Comments

Popular posts from this blog

sql server - Cannot query correctly (MSSQL - PHP - JSON) -

php - trouble displaying mysqli database results in correct order -

C++ Linked List -