Golang reflect.TypeOf() 函数的用法及示例
Go 语言内置支持运行时反射,并且允许程序通过反射包(reflect package)操纵任意类型的对象。
reflect.TypeOf() 函数在 Golang 中用于获取表示 i 的动态类型的反射类型。要访问此函数,需要在程序中导入反射包(reflect package)。
语法:
func TypeOf(i interface{}) Type
参数:
此函数仅接受一个接口(i)类型的参数。
返回值:
此函数返回反射类型。
以下示例说明了在 Golang 中使用上述方法:
示例 1:
// Golang program to illustrate
// reflect.TypeOf() Function
package main
import (
"fmt"
"reflect"
)
// Main function
func main() {
tst1 := "string"
tst2 := 10
tst3 := 1.2
tst4 := true
tst5 := []string{"foo", "bar", "baz"}
tst6 := map[string]int{"apple": 23, "tomato": 13}
// use of TypeOf method
fmt.Println(reflect.TypeOf(tst1))
fmt.Println(reflect.TypeOf(tst2))
fmt.Println(reflect.TypeOf(tst3))
fmt.Println(reflect.TypeOf(tst4))
fmt.Println(reflect.TypeOf(tst5))
fmt.Println(reflect.TypeOf(tst6))
}
输出:
string
int
float64
bool
[]string
map[string]int
示例 2:
// Golang program to illustrate
// reflect.TypeOf() Function
package main
import (
"fmt"
"io"
"os"
"reflect"
)
// Main function
func main() {
// use of TypeOf method
tt := reflect.TypeOf((*io.Writer)(nil)).Elem()
fileType := reflect.TypeOf((*os.File)(nil))
fmt.Println(fileType.Implements(tt))
}
输出:
true