What's the idiomatic way to write a method that operates on a "generic" array?
I have a typed array:
a := make([]int, 0)
I want to write a simple method that could operate on an array of any type:
func reverse(a []interface{}) []interface{} {
for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
a[i], a[j] = a[j], a[i]
}
return a
}
Using this method a = reverse(a)
gives me 2 errors:
cannot use a (type []int) as type []interface {} in argument to reverse
cannot use reverse(a) (type []interface {}) as type []int in assignment
Until generics arrive (which will most likely be called contracts), reflection and interfaces are the only tools to achieve such generalization.
You could define reverse()
to take a value of interface{}
and use the reflect
package to index it and swap elements. This is usually slow, and harder to read / maintain.
Interfaces provide a nicer way but requires you to write methods to different types. Take a look at the sort
package, specifically the sort.Sort()
function:
func Sort(data Interface)
Where sort.Interface
is:
type Interface interface {
// Len is the number of elements in the collection.
Len() int
// Less reports whether the element with
// index i should sort before the element with index j.
Less(i, j int) bool
// Swap swaps the elements with indexes i and j.
Swap(i, j int)
}
sort.Sort()
is able to sort any slices that implement sort.Interface
, any slices that have the methods the sorting algorithm needs to do its work. The good thing about this approach is that you can sort other data structures too not just slices (e.g. a linked list or an array), but usually slices are used.