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:
package main
import (
"fmt"
"reflect"
)
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)
}
|
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:
package main
import (
"fmt"
"reflect"
)
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)
}
|
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]
Last Updated :
28 Apr, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...