reflect.AppendSlice() Function in Golang with Examples

Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.AppendSlice() Function in Golang is used to appends a slice t to a slice s. To access this function, one needs to imports the reflect package in the program.

Syntax:

func AppendSlice(s, t Value) Value

Parameters: This function takes the following parameters:

  • s: This parameter is the slice.
  • t: This parameter is also an another slice.

Return Value: This function returns the resulting slice.

Below examples illustrate the use of above method in Golang:



Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Golang program to illustrate
// reflect.AppendSlice() Function
  
package main
  
import (
    "fmt"
    "reflect"
)
  
// Main function
func main() {
  
    val1:= reflect.ValueOf([]int{1, 2, 3, 4, 5})
      
    val2:= reflect.ValueOf([]int{11, 12, 13, 14, 15})
      
    fmt.Println("First Slice :", val1)
    fmt.Println("Second Slice :", val1)
      
    val1 = reflect.AppendSlice(val1, val2)
  
     fmt.Println("Resultant Slice :", val1)
      
  
}

chevron_right


Output:

First Slice : [1 2 3 4 5]
Second Slice : [1 2 3 4 5]
Resultant Slice : [1 2 3 4 5 11 12 13 14 15]

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Golang program to illustrate
// reflect.AppendSlice() Function
  
package main
  
import (
    "fmt"
    "reflect"
)
  
// Main function
func main() {
  
    var str []string
     var v reflect.Value = reflect.ValueOf(&str)
  
     v = v.Elem()
  
  
     v = reflect.Append(v, reflect.ValueOf("a"))
     v = reflect.Append(v, reflect.ValueOf("b"))
     v = reflect.Append(v, reflect.ValueOf("c"), reflect.ValueOf("j, k, l"))
      
    x:= []string{"m", "p", "s"}
      
    fmt.Println("First Slice :", v)
    fmt.Println("Second Slice :", x)
    v = reflect.AppendSlice(v, reflect.ValueOf(x))
  
     fmt.Println("Resultant Slice :", v)
  
}

chevron_right


Output:

First Slice : [a b c j, k, l]
Second Slice : [m p s]
Resultant Slice : [a b c j, k, l m p s]



My Personal Notes arrow_drop_up

Recommended Posts:

    Article Tags :

    Be the First to upvote.


    Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.