Golang reflect.MakeSlice() function example

package reflect

Golang reflect.MakeSlice() function usage example.

 package main

 import (
  "fmt"
  "reflect"
 )

 func main() {
  var str []string // must be a slice type for reflect.MakeSlice() to work

  var strValue reflect.Value = reflect.ValueOf(&str)

  indirectStr := reflect.Indirect(strValue)

  valueSlice := reflect.MakeSlice(indirectStr.Type(), 100, 1024) // otherwise, will panice

  kind := valueSlice.Kind()

  cap := valueSlice.Cap()

  length := valueSlice.Len()

  fmt.Printf("valueMap type is [%v] with capacity of %v bytes and length of %v .", kind, cap, length)

 }

Output :

valueMap type is [slice] with capacity of 1024 bytes and length of 100 .

Reference :

http://golang.org/pkg/reflect/#MakeSlice

Advertisement