Go (Golang) Modify Slices

Go (Golang) Modify Slices – Complete Guide with Examples
In Go (Golang), slices are reference-like data types, which means modifying a slice can also affect the original data. This makes slices powerful but tricky if you don’t understand how modification works.
This guide explains how to modify slices safely and correctly.
What Is a Slice in Go? (Quick Recall)
A slice is a dynamic, flexible view of an array.
- Can grow or shrink
- Passed by reference (internally)
Modifying Slice Elements
You can directly modify slice elements using an index.
Output
- Change reflects immediately
Slice Modification Inside a Function (Very Important)
Slices are passed by reference-like behavior.
Output
- Original slice is modified
Modifying Slice Length Using append()
Add Elements
- Slice grows dynamically
Important: append() May Create a New Slice
- If capacity is exceeded, Go allocates new memory.
- Always reassign result of
append()
Removing Elements from a Slice
Remove by Index
Output
- Common Go pattern
Modifying Slice Using range
Wrong Way
Correct Way
- Always use index to modify
Copying a Slice Before Modifying
To avoid changing the original slice, make a copy.
- Original remains unchanged
Modifying Slice Capacity with make()
| Property | Value |
|---|---|
| Length | 3 |
| Capacity | 5 |
- Controls memory behavior
Slice of Slices Modification
- Nested slice modification works
Nil Slice Modification
- Safe
- No panic
Common Mistakes
- Forgetting to reassign
append() Modifying slice value inrangeincorrectly- Assuming slices are copied automatically
- Index out of range panic
- Unintended shared memory
Best Practices for Modifying Slices
- Use index to modify elements
- Reassign result of
append() Copy slice when isolation is needed- Be careful with shared slices
- Prefer
make()for performance
Interview Questions: Go Slice Modification
1. Are slices passed by value or reference?
Reference-like behavior.
2. Does modifying a slice in a function affect original?
Yes.
3. Does range allow modification?
Only via index, not value.
4. Can append() change underlying array?
Yes.
5. How to safely modify without affecting original?
Use copy().
Summary
- Slice elements can be modified directly
- Changes reflect across references
append()may reallocate memory- Use index-based loops for modification
- Copy slices to avoid side effects
Mastering slice modification in Go is critical for performance, correctness, and interview success
