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]
.