public
Created

Simple demonstration of generics-like features in Go.

  • Download Gist
README.md
Markdown

POLYMORPHISM AND GENERICS IN GO

Lately, Go has been getting a lot of flack for its lack of generics and parametric polymorphism. Whereas it doesn't have a specific language feature called "generics", generic type operations are very simple to implement. Here is a simple implementation of a generic collection type in Go demonstrating how it's done. Essentially, the type interface{} acts as a placeholder for any type. By making use of the empty interface, you can pass any type to a function much like you can in dynamically-typed languages.

generics.go
Go
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
package main
 
import (
"fmt"
"reflect"
)
 
type CustomCollection struct {
myElements []interface{}
}
 
func (c *CustomCollection) init() {
c.myElements = nil
}
 
func (c *CustomCollection) add(element interface{}) {
eLen := len(c.myElements)
elements := make([]interface{}, eLen + 1)
copy(elements, c.myElements)
elements[eLen] = element
c.myElements = elements
}
 
func main() {
stringCollection := []string{"one", "two", "three"}
intCollection := []int{1, 2, 3}
fmt.Println("The value of stringCollection is: ", stringCollection)
fmt.Println("Now let's add it to a custom collection...")
myCollection := new(CustomCollection)
for _, v := range stringCollection {
myCollection.add(v)
}
fmt.Println("The value of myCollection.myElements is: ", myCollection.myElements)
fmt.Println("The type of myCollection.myElements is: ", reflect.TypeOf(myCollection.myElements))
fmt.Println("Now let's do it with ints...")
fmt.Print("The value of intCollection is: ", intCollection, "\n\n")
fmt.Println("And now we're creating a custom collection with the same values...")
myCollection = new(CustomCollection)
for _, v := range intCollection {
myCollection.add(v)
}
fmt.Println("The value of myCollection.myElements is: ", myCollection.myElements)
fmt.Println("The type of myCollection.myElements is: ", reflect.TypeOf(myCollection.myElements))
}

Although this has nothing to do with your polymorphism, you should know your "add" method can be quite a bit simpler if you use the builtin append() method. "c.myElements = append(c.myElements, element)" would replace the entire function implementation, except possibly a nil check on c.myElements.

@mfenniak append works just fine on nil slices, due to the simple fact that capacity for nil slices is defined as 0.

(On a side note, it would also make add a lot more efficient)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.