Can someone explain copying for slices

Can someone please provide an explanation on how the copy method with slices is used…

I want to delete a specific index of a slice… and then insert something bask into the slice, in that exact index…

I know how I would do it all, other than how i would move everything after that specific index over one… and then add something else in its place. This is to simulate the entry in the slice being edited…

Hope someone can help :slight_smile:

The below code removes it and i need to append back to the slice, in place of ‘oldindex’…

for i, va := range data[k] {
		if i == vi {
			toedit = true
			oldindex = i

		if toedit {
			if len(data[k])-1 == i {
				data[k] = data[k][:i]
			} else {
				data[k] = append(data[k][:i], data[k][i+1:]...)
			//append back to the index we just removed...


So if we have this slice originally:

[1, 2, 3, 4, 5, 6]

I want to delete index 2 and replace it with the value given in a POST request… lets say the new value was 10, it would look like this

[1, 2, 10, 4, 5, 6]

Hopefully that’s a little more clear

‘Append’ usually means ‘add at the end’. Is that what you want to do? Perhaps things will be more clear if you add an example: Given input [a, b, c, d, e], item f to insert, and index 2, would the expected result be [a, b, f, d, e]?

My apologies, I definitely could have been more clearer… please see update

1 Like

Have you considered simply replacing the element?


Believe it or not, i came across this after uploading this post. Thank you! It does work :slight_smile:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.