I know there are len()
and cap()
functions that return len/cap of slice, but I want to get address of slice to modify it by hand.
package main
import (
"fmt"
"reflect"
"unsafe"
)
func main() {
// slice of int
us := []int{1, 2, 3, 4}
// len: 4, cap: 4
fmt.Printf("len: %d, cap: %v\n", len(us), cap(us))
hdr := (*reflect.SliceHeader)(unsafe.Pointer(&us))
hdr.Cap = 10
hdr.Len = 100
// len: 100, cap: 10
fmt.Printf("len: %d, cap: %v\n", len(us), cap(us))
}
Sample output:
len: 4, cap: 4
len: 100, cap: 10