Session
Writing Ruby-like Functions and Methods in Go using Generics
This session is about how to write functions presenting the flexible APIs offered by languages such as Ruby without sacrificing more of the type safety offered by Go than is strictly necessary. Then how to test them and evaluate their performance without excessive code bloat.
Lots of fun will be had with Interfaces, Type Switches, Generics, and go test.
I love Go but have always found the way it handles collection types somewhat frustrating. In languages such as Ruby the collection classes are fleshed out with lots of functionality (ie batteries included) that in Go we have to roll for ourselves.
It’s not that the same things can’t be done, it’s that there’s no clear template for how to go about doing so consistently. And as the language provides a number of orthogonal data types for collections it makes sense to design functions which can work across them.
As a consequence of this I’ve been working on various packages for collection handling in Go for more than a decade now, some of them more practical than others.
Another of my interests is the use of Higher-Order Functions and Interfaces in API design. This topic doesn’t seem to get a lot of coverage despite Go having First-Class Function Closures. We’ll look at how to leverage Closures to write flexible functions and methods with strong type safety guarantees, as well as how to loosen those restrictions at runtime using Type Switches and Interfaces.
There was one very frustrating problem with these techniques prior to the introduction of Generics - the amount of code repetition necessary to support even the relatively small set of base types. This could be tackled using Reflection but that essentially abandons the speed of compiled code in favour of runtime interpretation as well as further degrading type safety. I don’t have a big problem with this on my personal projects but I feel bad doing it in production code.
Generics aren’t currently a perfect solution but they are very helpful so I’ll use them extensively throughout my examples and contrast them with alternative approaches where time allows.
Testing also benefits from both Closures and Generics so I’ll include examples of test code using both to write declarative tests and then to reduce the amount of code repetition involved. The same principles apply to benchmarking so we'll explore these as well.
If time allows I’ll include a Reflection example to highlight how much more legible Generic Functions are and also how much better their performance is.
By the end of the session I’ll have covered these topics in sufficient depth that anyone with a basic knowledge of Go will be able to have fun exploring further.
Please note that Sessionize is not responsible for the accuracy or validity of the data provided by speakers. If you suspect this profile to be fake or spam, please let us know.
Jump to top