Golang reflect.PtrTo() 函数及示例
Go 语言提供了内置支持运行时反射的实现,并使用 reflect 包让程序能够操作任意类型的对象。reflect.PtrTo() 函数用于获取元素 t 的指针类型,即 t 代表类型为 Geek,PtrTo(t) 代表 *Geek。为了访问此函数,需要在程序中导入 reflect 包。
语法:
func PtrTo(t Type) Type
参数: 此函数仅接受一个 Type 类型的参数(t)。
返回值: 此函数返回元素 t 的指针类型。
下面的示例演示了 Golang 中使用上述方法的情况:
示例 1:
// Golang program to illustrate
// reflect.PtrTo() Function
package main
import (
"fmt"
"reflect"
)
// Main function
func main() {
ta := reflect.ArrayOf(5, reflect.TypeOf(123))
// use of PtrTo method
tp := reflect.PtrTo(ta)
fmt.Println(tp)
}
输出:
*[5]int
示例 2:
// Golang program to illustrate
// reflect.PtrTo() Function
package main
import (
"fmt"
"reflect"
)
// Main function
func main() {
v := reflect.TypeOf("123")
// use of PtrTo method
fmt.Println(reflect.PtrTo(v))
}
输出:
*string