使用反射附加去朗片 [英] Appending to go lang slice using reflection

查看:35
本文介绍了使用反射附加去朗片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于某种原因,似乎使用反射向切片添加新元素不会更新切片本身.这是演示代码:

 程序包主要进口 ("fmt"反映")func appendToSlice(arrPtr interface {}){valuePtr:= reflect.ValueOf(arrPtr)值:= valuePtr.Elem()值= reflect.Append(值,reflect.ValueOf(55))fmt.Println(value.Len())//打印1}func main(){arr:= [] int {}appendToSlice(& arr)fmt.Println(len(arr))//打印0} 

游乐场链接: https://play.golang.org/p/j3532H_mUL

这里有什么我想念的吗?

解决方案

reflect.Append 的作用类似于 append ,因为它返回了一个新的slice值.

您正在将此值分配给 appendToSlice 函数中的 value 变量,该函数替代了以前的 reflect.Value ,但不会更新原始论点.

为了更清楚地说明正在发生的事情,请将等效函数用于您的示例,而无需进行反思:

  func appendToSlice(arrPtr * [] int){值:= * arrPtr值=追加(值,55)fmt.Println(len(value))} 

您需要使用的是 Value.Set 方法来更新原始值:

  func appendToSlice(arrPtr接口{}){valuePtr:= reflect.ValueOf(arrPtr)值:= valuePtr.Elem()value.Set(reflect.Append(value,reflect.ValueOf(55)))fmt.Println(value.Len())} 

https://play.golang.org/p/Nhabg31Sju

For some reason, it appears that adding new element to slice using reflection doesn't update slice itself. This is the code to demonstrate:

package main

import (
    "fmt"
    "reflect"
)

func appendToSlice(arrPtr interface{}) {
    valuePtr := reflect.ValueOf(arrPtr)
    value := valuePtr.Elem()
    value = reflect.Append(value, reflect.ValueOf(55))

    fmt.Println(value.Len()) // prints 1
}

func main() {
    arr := []int{}
    appendToSlice(&arr)
    fmt.Println(len(arr)) // prints 0
}

Playground link : https://play.golang.org/p/j3532H_mUL

Is there something I'm missing here?

解决方案

reflect.Append works like append in that it returns a new slice value.

You are assigning this value to the value variable in the appendToSlice function, which replaces the previous reflect.Value, but does not update the original argument.

To make it more clear what's happening, take the equivalent function to your example without reflection:

func appendToSlice(arrPtr *[]int) {
    value := *arrPtr
    value = append(value, 55)
    fmt.Println(len(value))
}

What you need to use is the Value.Set method to update the original value:

func appendToSlice(arrPtr interface{}) {
    valuePtr := reflect.ValueOf(arrPtr)
    value := valuePtr.Elem()

    value.Set(reflect.Append(value, reflect.ValueOf(55)))

    fmt.Println(value.Len())
}

https://play.golang.org/p/Nhabg31Sju

这篇关于使用反射附加去朗片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆