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

Pairing Up Two Slices (the zip operation)

In this lesson you will learn to pair up two slices in Go, so related data can be handled together. This is for anyone searching for "Go zip operation how to use".

Combining two corresponding slices - a list of names and a list of scores, say - into pairs one by one is called a zip operation. Go has no dedicated function, so you combine them one at a time with a for loop.

The sample code uses a shared index with for i := range names and prints each pair by combining names[i] and scores[i] with fmt.Printf. Reaching both slices with the same index is the whole idea.

A common stumbling block for beginners is what to do when the two slices are different lengths. Deciding and implementing that behaviour yourself is characteristically Go.

In real-world development the same shared-index approach extends directly to combining three or more slices.

๐Ÿ“– 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)