Golang reflect.AppendSlice() function example

package reflect

Golang reflect.AppendSlice() function 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)

  v = reflect.AppendSlice(v, reflect.ValueOf([]string{"mno", "pqr", "stu"}))

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

  fmt.Println("After AppendSlice : ", vSliceElems)

 }

Output :

Our value is a type of : slice

With the elements of : [abc def ghi jkl]

After AppendSlice : [abc def ghi jkl mno pqr stu]

Reference :

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

Advertisement