Append in slices creates a new underlying array
package main | |
import ( | |
"fmt" | |
"reflect" | |
"unsafe" | |
) | |
func main() { | |
vegies := [...]string{"Potato", "Tomato", "Eggplant", "Onion", "Capsicum"} | |
vegslice := vegies[1:3] | |
/* Returns | |
[Tomato Eggplant] 2 4 | |
Pointer to the underlying array 824634236944 */ | |
fmt.Println(vegslice, len(vegslice), cap(vegslice)) | |
hdr0 := (*reflect.SliceHeader)(unsafe.Pointer(&vegslice)) | |
fmt.Println("Pointer to the underlying array", hdr0.Data) | |
vegslice = append(vegslice, "Okra", "Cabbage") | |
/* Returns | |
[Tomato Eggplant Okra Cabbage] 4 4 | |
Pointer to the underlying array 824634236944 */ | |
fmt.Println(vegslice, len(vegslice), cap(vegslice)) | |
hdr := (*reflect.SliceHeader)(unsafe.Pointer(&vegslice)) | |
fmt.Println("Pointer to the underlying array", hdr.Data) | |
vegslice = append(vegslice, "Lettuce", "Bottlegaurd") | |
/* Returns [Tomato Eggplant Okra Cabbage Lettuce Bottlegaurd] 6 8 | |
Pointer to the underlying array 824634245120 << Changed */ | |
fmt.Println(vegslice, len(vegslice), cap(vegslice)) | |
hdr2 := (*reflect.SliceHeader)(unsafe.Pointer(&vegslice)) | |
fmt.Println("Pointer to the underlying array", hdr2.Data) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment