This question is about the cleanest way to "inherit" interface implementations in golang. I understand Go does not have inheritance; this question is about how people achieve it otherwise, hence the quotes around inheritance.
Let's say theres a standard library interface defined, for example container/heap
: https://golang.org/pkg/container/heap/#Interface
Lets say there's a .go
file called pq.go
that implements that interface:
//pq.go
import ("container/heap")
type PriorityQueue []*Vertex
func (pq PriorityQueue) Len() int { return len(pq) }
func (pq PriorityQueue) Less(i, j int) bool {
...
}
func (pq PriorityQueue) Swap(i, j int) {
...
}
func (pq *PriorityQueue) Push(x interface{}) {
...
}
func (pq *PriorityQueue) Pop() interface{} {
...
}
Now let's say I just want a Tiny variant on this, called MaxPQ
, in maxpq.go
, for where I want to override a single implementation detail of pq.go
, e.g., override Less(..)
. How do I achieve this without literally copying the last file over, changing the type name, and changing the implementation of the single function, e.g., less
?
Meaning, is there a way to make a new implementation of an interface that is very similar to another?
Doing this, literally copying it over, seems drastic and changes would need to be made in multiple places:
//maxpq.go
import ("container/heap")
type MaxPriorityQueue []*Vertex
func (pq MaxPriorityQueue) Len() int { return len(pq) }
func (pq MaxPriorityQueue) Less(i, j int) bool {
...
}
func (pq MaxPriorityQueue) Swap(i, j int) {
...
}
func (pq *MaxPriorityQueue) Push(x interface{}) {
...
}
func (pq *MaxPriorityQueue) Pop() interface{} {
...
}