Open In App

reflect.MakeMapWithSize() Function in Golang with Examples

Last Updated : 03 May, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report
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.MakeMapWithSize() Function in Golang is used to create a new map with the specified type and initial space for approximately n elements. To access this function, one needs to imports the reflect package in the program.
Syntax:
func MakeMapWithSize(typ Type, n int) Value
Parameters: This function takes the following parameters:
  • typ : This parameter is the Type.
  • n: This parameter is the number of elements.
Return Value: This function returns a newly created map.
Below examples illustrate the use of above method in Golang: Example 1: C
// Golang program to illustrate
// reflect.MakeMapWithSize() Function
  
package main
  
import (
    "fmt"
    "reflect"
)
 
// Main function
func main() {
 
    var str map[int]string 
    var n int
    n=10
     
    var strValue reflect.Value = reflect.ValueOf(&str)
 
    indirectStr := reflect.Indirect(strValue)
     
    //Use of MakeMapWithSize() method
 
    valueMap := reflect.MakeMapWithSize(indirectStr.Type(), n)
     
    fmt.Printf("ValueMap is [%v] .", valueMap)
 
}
Output:
ValueMap is [map[]] .
Example 2: C
// Golang program to illustrate
// reflect.MakeMapWithSize() 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.MakeMapWithSize(mapType, 100)
 
    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]

Next Article

Similar Reads