Golang reflect.MapOf() 函数及示例
Go 语言提供了内置的实现运行时反射的支持,并通过反射包帮助程序操作具有任意类型的对象。 Golang 中的 reflect.MapOf() 函数用于获取具有给定键和元素类型的映射类型,例如如果 k 表示 int,e 表示 string,则 MapOf(k, e) 表示 map[int]string。 要访问此函数,需要在程序中导入反射包。
语法:
func MapOf(key, elem Type) Type
参数: 此函数接受 Type 类型的三个参数(键、元素类型)。
返回值: 此函数返回具有给定键和元素类型的映射类型。
以下示例说明了在 Golang 中使用上述方法的用法:
示例 1:
// Golang 程序演示
// reflect.MapOf() 函数
package main
import (
"fmt"
"reflect"
)
// 主函数
func main() {
var i interface{}
// 使用 MapOf 方法
tm := reflect.MapOf(reflect.TypeOf("string"),
reflect.TypeOf(&i).Elem())
fmt.Println(tm)
}
输出:
map[string]interface {}
示例 2:
// Golang 程序演示
// reflect.MapOf() 函数
package main
import (
"fmt"
"reflect"
)
// 主函数
func main() {
ta := reflect.ArrayOf(5, reflect.TypeOf(123))
tc := reflect.ChanOf(reflect.SendDir, ta)
// 使用 MapOf 方法
tm := reflect.MapOf(ta, tc)
fmt.Println(tm)
}
输出:
map[[5]int]chan<- [5]int