📜  Golang 中的reflect.MakeSlice()函数示例

📅  最后修改于: 2021-10-25 02:19:20             🧑  作者: Mango

Go 语言提供了运行时反射的内置支持实现,并允许程序在反射包的帮助下操作任意类型的对象。 Golang 中的 reflect.MakeSlice()函数用于为指定的零初始化切片值创建新的切片类型、长度和容量。要访问此函数,需要在程序中导入反射包。

下面的例子说明了上述方法在 Golang 中的使用:

示例 1:

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

输出:

// 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)
   
    
}

示例 2:

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

输出:

// 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)
   
}