Golang reflect.ValueOf()函数及示例
Go语言提供了内置支持运行时反射的实现,并允许程序通过reflect包来操纵任意类型的对象。Golang中的 reflect.ValueOf() 函数被用来获取在接口i中储存的具体值的新值。要访问此函数,需要将reflect包引入程序中。
语法:
func ValueOf(i interface{}) Value
参数: 此函数需要以下参数:
- i: 此参数为接口。
返回值: 此函数返回一个被初始化为接口i中储存的具体值的新值。
下面的例子演示了如何在Golang中使用上述方法:
例1:
// Golang program to illustrate
// reflect.ValueOf() Function
package main
import (
"fmt"
"reflect"
)
// 主函数
func main() {
a := []int{2, 5}
var b reflect.Value = reflect.ValueOf(&a)
b = b.Elem()
fmt.Println("切片 :", a)
// 使用ValueOf方法
b = reflect.Append(b, reflect.ValueOf(80))
fmt.Println("追加数据后的切片:", b)
} ```
输出:
切片: [2 5]
追加数据后的切片: [2 5 80]
例2:
// Golang program to illustrate
// reflect.ValueOf() Function
package main
import (
"fmt"
"reflect"
)
// 主函数
func main() {
src := reflect.ValueOf([]int{10, 20, 32})
dest := reflect.ValueOf([]int{1, 2, 3})
// 使用ValueOf()方法
fmt.Println(src, dest)
}
输出:
[10 20 32] [1 2 3]