Skip to content

Instantly share code, notes, and snippets.

@cjgiridhar
Created January 27, 2019 07:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cjgiridhar/1b44d5fd34a9d260809d07cbd10145e9 to your computer and use it in GitHub Desktop.
Save cjgiridhar/1b44d5fd34a9d260809d07cbd10145e9 to your computer and use it in GitHub Desktop.
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