Golang reflect.Append() function and reflect.Value methods example

package reflect

Golang reflect.Append() function and reflect.Value methods usage example

 package main

 import (
  "fmt"
  "reflect"
 )

 func main() {
  var str []string
  var v reflect.Value = reflect.ValueOf(&str)

  // make value to adopt element's type - in this case string type

  v = v.Elem()


  v = reflect.Append(v, reflect.ValueOf("abc"))
  v = reflect.Append(v, reflect.ValueOf("def"))
  v = reflect.Append(v, reflect.ValueOf("ghi"), reflect.ValueOf("jkl"))

  fmt.Println("Our value is a type of :", v.Kind())

  vSlice := v.Slice(0, v.Len())
  vSliceElems := vSlice.Interface()

  fmt.Println("With the elements of : ", vSliceElems)

 }

Output :

Our value is a type of : slice

With the elements of : [abc def ghi jkl]

References :

http://golang.org/pkg/reflect/#Value.Slice

http://golang.org/pkg/reflect/#Value.Interface

http://golang.org/pkg/reflect/#Value.Len

http://golang.org/pkg/reflect/#Value.Elem

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

Advertisement