How to remove an element from a slice in Golang: correct ways
Hello everyone! I just started learning Go and encountered a problem when working with slices. I need to remove an element by index, but I can't find a built-in function that does this. In Python I'm used to `list.pop()` or `del list[i]`, but Go doesn't have that.
Here's what I tried:
```go
package main
import "fmt"
func main() {
fruits := []string{"apple", "banana", "cherry", "date"}
// Want to remove "banana" (index 1)
// Tried to assign nil - doesn't work
// fruits[1] = nil // compilation error
// Tried to do a slice, but it turns out wrong
result := append(fruits[:1], fruits[2:]...)
fmt.Println(result) // outputs: [apple cherry date]
fmt.Println(fruits) // outputs: [apple cherry date date] - bug!
// Why does the original slice
No answers yet.
Log in to leave an answer