Go 语言提供了运行时反射的内置支持实现,并允许程序在反射包的帮助下操作任意类型的对象。 Golang 中的reflect.Append()函数用于将值x 追加到切片s 中。要访问此函数,需要在程序中导入反射包。
Syntax:
Parameters: This function takes the following parameters:
- s: This parameter is the slice where values are to be append.
- x: These parameter are values to be append.
Return Value: This function returns the resulting slice.
下面的例子说明了上述方法在 Golang 中的使用:
示例 1:
func Append(s Value, x ...Value) Value
输出:
// Golang program to illustrate
// reflect.Append() Function
package main
import (
"fmt"
"reflect"
)
// Main function
func main() {
a := []int{2, 5}
var b reflect.Value = reflect.ValueOf(&a)
b = b.Elem()
fmt.Println("Slice :", a)
// use of Append method
b = reflect.Append(b, reflect.ValueOf(80))
fmt.Println("Slice after appending data:", b)
}
示例 2:
Slice : [2 5]
Slice after appending data: [2 5 80]
输出:
// Golang program to illustrate
// reflect.Append() Function
package main
import (
"fmt"
"reflect"
)
// Main function
func main() {
var str []string
var v reflect.Value = reflect.ValueOf(&str)
v = v.Elem()
// using the function
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"))
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)
}