0
0
Goprogramming~3 mins

Why Slice and array relationship in Go? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could share just the part you want without making extra copies every time?

The Scenario

Imagine you have a big box of colored pencils (an array), and you want to share just a few colors with your friend without giving away the whole box.

Manually, you might try to copy those few pencils into a new smaller box every time you want to share, which takes time and space.

The Problem

Copying parts of the big box again and again is slow and wastes space.

If you forget to update the copies when the original changes, your friend might get outdated colors.

It's like making many small boxes instead of just pointing to the pencils you want to share.

The Solution

Slices let you create a view or window into the big box without copying pencils.

You can share just the part you want, and if the original pencils change, the slice sees the change too.

This saves time and memory, making your program faster and simpler.

Before vs After
Before
var colors [5]string = [5]string{"red", "blue", "green", "yellow", "purple"}
var sharedColors [2]string
sharedColors[0] = colors[1]
sharedColors[1] = colors[2]
After
var colors = [5]string{"red", "blue", "green", "yellow", "purple"}
sharedColors := colors[1:3]
What It Enables

It enables efficient, flexible access to parts of data without extra copying or memory waste.

Real Life Example

When you watch a part of a video, slices let the player show just that segment without copying the whole video file.

Key Takeaways

Slices are like windows into arrays, not copies.

They save time and memory by sharing data.

Changes in the original array reflect in slices.