There is no function to unset the element in array, but we can use the slice.
In example
1 | numbers := []int{2, 4, 6, 8, 10, 12, 14, 16, 18, 20} |
We want to remove the 3rd index, become this.
1 | []int{2, 4, 6, 10, 12, 14, 16, 18, 20} |
So define indexRemove first.
1 | indexRemove := 3 |
Then we slice from index 0, and get until index 2. Example.
1 2 3 4 5 6 7 | var firstSlice []int = numbers[:indexRemove] fmt.Println("firstSlice:") fmt.Println(firstSlice) // result firstSlice: [2 4 6] |
Then slice from index 4 to last index 9. Example.
1 2 3 4 5 6 7 | var lastSlice []int = numbers[indexRemove + 1:] fmt.Println("lastSlice:") fmt.Println(lastSlice) // result lastSlice: [10 12 14 16 18 20] |
Then combine or append into one array. Example.
1 2 3 4 5 6 | numbersWithout3rdIndex := append(firstSlice, lastSlice) fmt.Println("numbersWithout3rdIndex:") fmt.Println(numbersWithout3rdIndex) // result cannot use lastSlice (type []int) as type int in append |
But it show some error because 2nd parameter in method append() want to …Type. So we change the code. Reference.
1 2 3 4 5 | numbersWithout3rdIndex := append(firstSlice, lastSlice...) // result numbersWithout3rdIndex: [2 4 6 10 12 14 16 18 20] |
The the logic is append first slice and last slice. And we can simplify like this.
1 2 3 4 5 6 7 8 9 10 | indexRemove := 3 numbers := []int{2, 4, 6, 8, 10, 12, 14, 16, 18, 20} numbersWithout3rdIndex := append(numbers[:indexRemove], numbers[indexRemove + 1:]...) fmt.Println("numbersWithout3rdIndex:") fmt.Println(numbersWithout3rdIndex) // result numbersWithout3rdIndex: [2 4 6 10 12 14 16 18 20] |