The Startup
Published in

The Startup

Experimenting with generics in Go

Photo by Louis Reed on Unsplash
type List(type T) struct {
elems []T
}
class MyList<T> {
private List<T> elements = new ArrayList<>();
}
func (this *List(T)) Size() int {
return len(this.elems)
}
func (this *List(T)) Add(e T) *List(T) {
this.elems = append(this.elems, e)
return this
}
list.Add("A").Add("B").Add("C")
var listOfNumbers List(int)
list.Add(1).Add(2).Add("A") // cannot convert "A" to int
func (this *List(T)) Get(i int) T {
return this.elems[i]
}
func (this *List(T)) Foreach(f func(T)) {
for i := 0; i < this.Size(); i++ {
f(this.Get(i))
}
}
func (this *List(T)) Filter(f func(T) bool) *List(T) {
var res List(T)
for i := 0; i < this.Size(); i++ {
e := this.Get(i)
if f(e) {
res.Add(e)
}
}
return &res
}
func Map(type F, T)(list List(F), f func(F) T) *List(T) {
var res List(T)
for i := 0; i < list.Size(); i++ {
e := list.Get(i)
res.Add(f(e))
}
return &res
}
class MyList<T> {
public <R> MyList<R> map(Function<T, R> mapper) {
...
}
}
func main() {
var listOfNumbers List(int)
for i := 1; i <= 10; i++ {
listOfNumbers.Add(i)
}
// Now we can have nice Filter and Foreach in Go!
listOfNumbers.Filter(func(i int) bool {
return i%2 == 0
}).Foreach(func(i int) {
fmt.Println(i)
})
// And Map is also not that bad
listOfStrings := Map(listOfNumbers, func(i int) string {
s := strconv.Itoa(i)
return s + s
})
// The most important part - it's generic!
listOfStrings.Foreach(func(s string) {
fmt.Println(s)
})
}

Conclusions

--

--

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +760K followers.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Alexey Soshin

Solutions Architect @Depop, author of “Kotlin Design Patterns and Best Practices” book and “Pragmatic System Design” course