Ad space (banner)
๐ŸนGo Lessons
Lesson 23 / 68

Transforming a Slice (a map-like Operation)

In this lesson you will learn how to transform every element of a slice in Go so you can process data in bulk. This is for anyone searching for "Go slice map transform".

Go has no standard map() function like some languages, but building a new slice in a for loop does the same job. Think of it as a machine on a conveyor belt that processes every product that passes through it in the same way.

The sample code has mapInts() take a function f func(int) int as an argument, walk the original slice with for i, n := range nums, and store each converted value with result[i] = f(n). Passing the function in makes it a general-purpose helper whose transformation rule can simply be swapped out.

A common stumbling block for beginners is having to size the result slice in advance with make([]int, len(nums)). You could build it with append alone, but reserving the length with make is more efficient when the size is known.

In real-world development this shape comes up whenever you process data in bulk, such as applying tax to prices or converting units.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Go directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)