Golang reflect.New() 函数的实例
Go 语言内置支持运行时反射,使用 reflect 包可以帮助程序处理任意类型的对象。reflect.New() 函数用于获取表示指向特定类型的新零值的值。要使用此函数,需要在程序中导入 reflect 包。
语法:
func New(typ Type) Value
参数: 此函数接受以下参数:
- typ: 此参数为 Type 类型。
返回值: 此函数返回表示指向特定类型的新零值的值。
以下示例说明如何在 Golang 中使用该方法:
示例 1:
// Golang 程序示例
// 展示 reflect.New() 函数
package main
import (
"fmt"
"reflect"
)
// 主函数
func main() {
t := reflect.TypeOf(5)
arr := reflect.ArrayOf(4, t)
inst := reflect.New(arr).Interface().(*[4]int)
for i := 1; i <= 4; i++ {
inst[i-1] = i*i
}
fmt.Println(inst)
}
输出:
&[1 4 9 16]
示例 2:
// Golang 程序示例
// 展示 reflect.New() 函数
package main
import (
"fmt"
"reflect"
)
type Geek struct {
A int 'tag1:"First Tag" tag2:"Second Tag"'
B string
}
// 主函数
func main() {
greeting := "GeeksforGeeks"
f := Geek{A: 10, B: "Number"}
gVal := reflect.ValueOf(greeting)
fmt.Println(gVal.Interface())
gpVal := reflect.ValueOf(&greeting)
gpVal.Elem().SetString("Articles")
fmt.Println(greeting)
fType := reflect.TypeOf(f)
fVal := reflect.New(fType)
fVal.Elem().Field(0).SetInt(20)
fVal.Elem().Field(1).SetString("Number")
f2 := fVal.Elem().Interface().(Geek)
fmt.Printf("%+v, %d, %s\n", f2, f2.A, f2.B)
}
输出:
GeeksforGeeks
Articles
{A:20 B:Number}, 20, Number