Go 语言提供了运行时反射的内置支持实现,并允许程序在反射包的帮助下操作任意类型的对象。 Golang 中的 reflect.MakeSlice()函数用于为指定的零初始化切片值创建新的切片类型、长度和容量。要访问此函数,需要在程序中导入反射包。
Syntax:
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 od slice.
Return Value: This function returns a newly created slice.
下面的例子说明了上述方法在 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)
}