reflect.MapOf() Function in Golang with Examples
Last Updated :
28 Apr, 2020
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.MapOf() Function in Golang is used to get the map type with the given key and element types, i.e., if k represents int and e represents string, MapOf(k, e) represents map[int]string. To access this function, one needs to imports the reflect package in the program.
Syntax:
func MapOf(key, elem Type) Type
Parameters: This function takes three parameters of Type type(key, elem).
Return Value: This function returns the map type with the given key and element types.
Below examples illustrate the use of the above method in Golang:
Example 1:
package main
import (
"fmt"
"reflect"
)
func main() {
var i interface{}
tm := reflect.MapOf(reflect.TypeOf( "string" ),
reflect.TypeOf(&i).Elem())
fmt.Println( tm )
}
|
Output:
map[string]interface {}
Example 2:
package main
import (
"fmt"
"reflect"
)
func main() {
ta := reflect.ArrayOf(5, reflect.TypeOf(123))
tc := reflect.ChanOf(reflect.SendDir, ta)
tm := reflect.MapOf(ta, tc)
fmt.Println( tm )
}
|
Output:
map[[5]int]chan<- [5]int
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...