Simple Example of Using Go Generics with Map
Go generics, introduced in version 1.18, allow developers to write flexible and type-safe functions that can operate on different data types. One practical application of generics is the implementation of the Map
function, which transforms elements of a collection. Below is a straightforward example demonstrating how to create and use a generic Map
function in Go.
package main
import "fmt"
// Generic Map function
func Map[T any, U any](input []T, f func(T) U) []U {
result := make([]U, len(input)) // Create a new slice for the results
for i, v := range input { // Iterate over each element in the input slice
result[i] = f(v) // Apply the function and store the result
}
return result // Return the new slice
}
func main() {
// Example input: a slice of integers
numbers := []int{1, 2, 3, 4, 5}
// Using the Map function to double each number
doubled := Map(numbers, func(n int) int {
return n * 2
})
// Output the results
fmt.Println("Original Numbers:", numbers) // Output: [1 2 3 4 5]
fmt.Println("Doubled Numbers:", doubled) // Output: [2 4 6 8 10]
}
In this example, we define a generic Map
function that takes a slice of any type T
and a function f
that transforms an element of type T
into another type U
. Inside the Map
function, we create a new slice to hold the transformed elements, iterate over the input slice, apply the transformation function to each element, and store the results in the new slice. In the main
function, we demonstrate how to use the Map
function by passing a slice of integers and a lambda function that doubles each number. The output shows both the original and the transformed slices, showcasing the effectiveness of generics in creating reusable and type-safe functions in Go.
Go 1.18 introduced generics, enabling type-safe and flexible functions. This article demonstrates a practical example of using generics to create a Map function that applies a transformation to elements in a collection, showcasing the implementation with a function that doubles each number in a slice of integers.