Go (Golang) Modify Slices

Go Tutorial

Go (Golang) Modify Slices

Slices are dynamic and reference-based, so understanding how to access, modify, append, and copy them is very important.


1️⃣ Access Slice Elements

Slice indexing starts from 0.


 

Access Using range



2️⃣ Change (Modify) Slice Elements

You can directly change values using index.


 

⚠ Slices are reference types:


 


3️⃣ Append Elements to Slice

Append Single Element


Append Multiple Elements


Append One Slice to Another


 

⚠ Always reassign:



4️⃣ Copy Slices (Important)

Direct assignment does NOT copy data.

❌ Wrong:


✔ Correct (use copy()):


 


5️⃣ Partial Copy


 


6️⃣ Copy with Append Trick


✔ Creates independent copy


7️⃣ Remove Elements from Slice

Remove element at index i


 


8️⃣ Access Sub-slices


 

⚠ Sub-slices share memory.


9️⃣ Common Mistakes

❌ Forgetting to reassign append()
❌ Expecting assignment to copy data
❌ Modifying sub-slices unintentionally


Summary Table

Operation Method
Access slice[i]
Modify slice[i] = value
Append append(slice, x)
Copy copy(dst, src)
Remove append(slice[:i], slice[i+1:]...)

You may also like...