gpt4 book ai didi

reflection - 在 golang 中将 interface{} 转换为 *[]int

转载 作者:IT王子 更新时间:2023-10-29 01:39:47 26 4
gpt4 key购买 nike

我收到一个基本上是 slice 的接口(interface)。现在我想将它转换为指向 slice 的指针。问题是,我要么有 slice 本身,要么有一个指向接口(interface)的指针。我可以在代码示例中轻松展示:

func main(){
model := []int{1,2,3,4,5,6,7,8,10,11,133123123123}
method(model)
}

func method(model interface{}){
fmt.Println(reflect.TypeOf(model)) // this is of type []int
fmt.Println(reflect.TypeOf(&model)) // this is of type *interface{}
}

我需要的是这个类型:

fmt.Println(reflect.TypeOf(result))    // this should be type *[]int

我只在运行时知道类型,因此我不能只接受 &(模型.([]int))

有没有办法使用 golang 反射来接收这个?这里的“int”类型实际上并不重要,重要的是,它是一个指向 slice 的指针*[]interface{} 也可以。

编辑:
为了使问题更清楚,我应该添加:我对 slice 的数据不感兴趣,而只对获取指向相同类型的 slice (基本上可以为空)的指针感兴趣。因此 James Henstridge 的回答非常有效。

最佳答案

在试图回答这个问题之前,有必要退后一步,问问您所追求的 *[]int 值应该指向什么?

鉴于 method 的调用方式,我们不可能从调用上下文中获取指向 model 变量的指针,因为它只会接收 slice 的副本作为其参数(请注意,这是 slice header 的副本:支持数组是共享的)。

我们也无法获得指向作为参数传递的副本的指针,因为它存储为 interface{} 变量:接口(interface)变量拥有用于存储其动态值的内存,并且当为其分配新值时,可以自由重用它。如果您可以获取指向动态值的指针,那么如果分配了不同的类型,这将破坏类型安全。

如果我们制作 slice 的第三个副本,我们可以获得一个 *[]int 指针,但不清楚这是否是您一定想要的:

v := reflect.New(reflect.TypeOf(model))
v.Elem().Set(reflect.ValueOf(model))
result := v.Interface()

这本质上是一种与类型无关的写法:

v := new([]int)
*v = model
var result interface{} = v

现在,如果您真的想要在调用上下文中指向 slice 变量的指针,则需要确保使用指向 slice 的指针调用方法,并采取相应的行动。

关于reflection - 在 golang 中将 interface{} 转换为 *[]int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26722655/

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