25% off

Use code FUNCMAIN at checkout for 25% off all premium courses.

Get started →
Mapping Over Slice Elements in Go
Code Snippet

Mapping Over Slice Elements in Go

go

Mapping over slice elements allows you to transform each element in a slice and collect the results into a new slice. This is a common functional programming pattern that works well in Go.

In this example, we create a new slice with the same capacity as the original and iterate through each element, applying a transformation (doubling each number) and storing the result at the corresponding index in the new slice. Pre-allocating the slice with make() is more efficient than appending repeatedly.

This approach is simple, efficient, and works with any transformation function. You can easily modify the transformation logic to suit your needs, whether that’s mathematical operations, string transformations, or more complex data conversions.

Further Reading: