gpt4 book ai didi

go - 获取和设置任意 slice 的长度

转载 作者:行者123 更新时间:2023-12-01 22:15:22 24 4
gpt4 key购买 nike

要获取任何 slice 的长度,我使用 reflect.ValueOf(slice).Len() .
要设置任何 slice 的长度,我使用 reflect.ValueOf(&slice).Elem().SetLen(n) .

我有一个类型为 reflect.Value 的字段在我的结构中,值设置为 reflect.ValueOf(&slice)这样我就可以更改 slice 。但现在我无法获得底层 slice 的长度。

它会因为 call of reflect.Value.Len on ptr Value 而 panic 如果我调用 Len()直接,和 call of reflect.Value.Len on interface Value如果我调用 Elem().Len() .

以下是我试图实现的功能:

func pop(slice interface{}) interface{} {
v := reflect.ValueOf(slice)
length := v.Len()
last := v.Index(length - 1)
v.SetLen(length - 1)
return last
}

我怎样才能同时使用 refect.Value slice 指针?

最佳答案

编写函数以使用指向 slice 参数的指针。

// pop removes and returns the last element from
// the slice pointed to by slicep.
func pop(slicep interface{}) interface{} {
v := reflect.ValueOf(slicep).Elem()
length := v.Len()
last := v.Index(length - 1)
v.SetLen(length - 1)
return last
}

像这样称呼它:
slice := []int{1, 2, 3}
last := pop(&slice)
fmt.Println(last) // prints 3
fmt.Println(slice) // prints [1 2]

Run it on the playground

关于go - 获取和设置任意 slice 的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60749931/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com