Member-only story
Introduction to Generic Programming in Go: Filtering and Summing Numeric Types
Go is a statically typed language with a strict type system, which means that each variable and function parameter must have a specific type defined at compile-time. While this makes Go programs fast and efficient, it can also make them less flexible and harder to write. To address this issue, Go 1.18 introduced support for generics, allowing programmers to write code that can work with a wide range of types.
In this tutorial, we’ll explore how to use generics to implement a filter function that works with numeric types. Our filter function will take a list of values and a predicate function that returns true or false based on whether a value should be included in the filtered list. Additionally, our filter function will return the sum of the filtered values.
Step 1: Defining the Numeric Interface
To implement our filter function, we’ll define a Numeric interface that all numeric types must satisfy. The Numeric interface will have two methods: Add and IsZero. The Add method will take another value and return the sum of the two values, while the IsZero method will return true if the value is zero.
type Numeric interface {
Add(x interface{}) Numeric
IsZero() bool
}
We’ll use the interface{} type to define the parameter type of the Add method, which will allow us to pass in any type of value to the method.