Skip to content
Related Articles
Open in App
Not now

Related Articles

reflect.MapOf() Function in Golang with Examples

Improve Article
Save Article
  • Last Updated : 28 Apr, 2020
Improve Article
Save Article

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:




// Golang program to illustrate
// reflect.MapOf() Function 
  
package main
  
import (
    "fmt"
    "reflect"
)
  
// Main function 
func main() {
  
    var i interface{}
      
    // use of MapOf method
    tm := reflect.MapOf(reflect.TypeOf("string"),
                      reflect.TypeOf(&i).Elem())
      
    fmt.Println(tm)
}

Output:

map[string]interface {}

Example 2:




// Golang program to illustrate
// reflect.MapOf() Function 
  
package main
  
import (
    "fmt"
    "reflect"
)
  
// Main function 
func main() {
  
    ta := reflect.ArrayOf(5, reflect.TypeOf(123))
      
    tc := reflect.ChanOf(reflect.SendDir, ta)
      
    //use of MapOf method
    tm := reflect.MapOf(ta, tc)
      
    fmt.Println(tm)
}

Output:

map[[5]int]chan<- [5]int

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!