package main
import "fmt"
func main() {
paths := []string{"hello", "world", "mars"}
var result = delete(paths, 1)
fmt.Println(result)
fmt.Println(paths)
}
func delete(paths []string, index int) []string {
paths = append(paths[:index], paths[index+1:]...)
return paths
}
The result of the code above is the following:
[hello mars]
[hello mars mars]
As you see, the second fmt.Println(paths)
obviously uses the modified slice but does not use the reassigned value. Why is that? I was expecting it to print [hello mars]
like in the print before.
I know that paths
being passed is not the same slice as paths
parameter in the delete()
function expect for referencing the same underlying array. But I still don't understand how I changed the underlying array of the paths
being passed to delete
function as it prints [hello mars mars]
instead of [hello world mars]
.
Because, as you said, the same underlying array is in use. When you do the append, paths[:1]
is a slice of length 1 and capacity 3, and paths[2:]
is a slice of length 1, so there is enough room in the underlying array of the first slice to append the new value without allocating a new array. paths
in main
is still a slice of length 3 since it was never modified, but since the underlying array was modified (specifically element 1), you see the value that you see.
You may want to take a look at https://blog.golang.org/go-slices-usage-and-internals if you haven't already.