Golang reflect.MakeSlice() 函数及示例
Go 语言提供反射的支持,通过反射包,程序可以操作任意类型的对象。Golang 中的 reflect.MakeSlice() 函数用于为指定的切片类型、长度和容量创建新的零值切片。使用该函数需要在程序中导入 reflect 包。
语法:
func MakeSlice(typ Type, len, cap int) Value
参数: 该函数需要以下参数:
- typ: 类型。
- len: 元素数量。
- cap: 切片容量。
返回值: 该函数返回一个新创建的切片。
以下示例演示了如何在 Golang 中使用上述方法:
示例 1:
// Golang 程序演示
// reflect.MakeMapWithSize() 函数
package main
import (
"fmt"
"reflect"
)
// 主函数
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)
}
输出:
Type is [slice] with capacity of 1024 bytes and length of 100 .
示例 2:
// Golang 程序演示
// reflect.MakeMapWithSize() 函数
package main
import (
"fmt"
"reflect"
)
// 主函数
func main() {
intSlice := make([]int, 0)
mapStringInt := make(map[string]int)
sliceType := reflect.TypeOf(intSlice)
mapType := reflect.TypeOf(mapStringInt)
// 使用 MakeSlice() 方法
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)
}
输出:
[100]
map[GeeksforGeeks:100]