Open In App

reflect.MakeSlice() Function in Golang with Examples

Improve
Improve
Like Article
Like
Save
Share
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.MakeSlice() Function in Golang is used to create new zero-initialized slice value for the specified slice type, length, and capacity. To access this function, one needs to imports the reflect package in the program.

Syntax:

func MakeSlice(typ Type, len, cap int) Value

Parameters: This function takes the following parameters:

  • typ : This parameter is the Type.
  • len: This parameter is the number of elements.
  • cap: This parameter is the capacity of slice.

Return Value: This function returns a newly created slice.

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 []string
      
    var strValue reflect.Value = reflect.ValueOf(&str)
  
    indirectStr := reflect.Indirect(strValue)
  
    valueSlice := reflect.MakeSlice(indirectStr.Type(), 100, 1024)
      
    kind := valueSlice.Kind()
  
    cap := valueSlice.Cap()
  
    length := valueSlice.Len()
  
    fmt.Printf("Type is [%v] with capacity of %v bytes"+
              " and length of %v .", kind, cap, length)
  
   
}


Output:

Type is [slice] with capacity of 1024 bytes and length of 100 .

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)
 
    //use of MakeSlice() method
    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]


Last Updated : 10 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads