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.MakeMap() Function in Golang is used to create a new map with the specified type. To access this function, one needs to imports the reflect package in the program.
Syntax:
func MakeMap(typ Type) ValueParameters: This function takes the following parameters:
- typ : This parameter is the Type.
Return Value: This function returns a newly created map.
Below examples illustrate the use of above method in Golang:
Example 1:
// Golang program to illustrate // reflect.MakeMap() Function package main import ( "fmt"
"reflect"
) // Main function func main() { var str map[ int ]string
var strValue reflect.Value = reflect.ValueOf(&str)
indirectStr := reflect.Indirect(strValue)
//Use of MakeMap() method
valueMap := reflect.MakeMap(indirectStr.Type())
fmt.Printf( "ValueMap is [%v] ." , valueMap)
} |
Output:
ValueMap is [map[]] .
Example 2:
// Golang program to illustrate // reflect.MakeMap() Function package main import ( "fmt"
"reflect"
) // Main function func main() { intSlice := make([] int , 0)
mapStringInt := make(map[string] int )
sliceType := reflect.TypeOf(intSlice)
mapType := reflect.TypeOf(mapStringInt)
intSliceReflect := reflect.MakeSlice(sliceType, 0, 0)
mapReflect := reflect.MakeMap(mapType)
v := 100
rv := reflect.ValueOf(v)
intSliceReflect = reflect.Append(intSliceReflect, rv)
intSlice2 := intSliceReflect.Interface().([] int )
fmt.Println(intSlice2)
k := "GeeksforGeeks"
rk := reflect.ValueOf(k)
mapReflect.SetMapIndex(rk, rv)
mapStringInt2 := mapReflect.Interface().(map[string] int )
fmt.Println(mapStringInt2)
} |
Output:
[100] map[GeeksforGeeks:100]
Article Tags :