doutou7961 2017-10-25 10:20
浏览 31
已采纳

使用反射附加到切片

I would like to append to a slice using only reflection. But I can't figure out how to "replace" the value of a with the new slice.

func main() {
    fmt.Println("Hello, playground")

    a := []string {"a","b","c"}

    values := []string {"d","e"}

    v := reflect.ValueOf(a)

    fmt.Printf("%t

", v.Type())
    fmt.Printf("%t

", v.Type().Elem().Kind())

    for _, val := range values {
        v.Set(reflect.Append(v, reflect.ValueOf(val)))
    }

    fmt.Printf("%t - %v", a, a)
}

This code is available for fiddling at https://play.golang.org/p/cDlyH3jBDS.

  • 写回答

1条回答 默认 最新

  • dscrb00804 2017-10-25 10:47
    关注

    You can't modify the value wrapped in reflect.Value if it originates from a non-pointer. If it would be allowed, you could only modify a copy and would cause more confusion. A slice value is a header containing a pointer to a backing array, a length and a capacity. When you pass a to reflect.ValueOf(), a copy of this header is made and passed, and any modification you could do on it could only modify this header-copy. Adding elements (and thus changing its length and potentially the pointer and capacity) would not be observed by the original slice header, the original would still point to the same array, and would still contain the same length and capacity values. For details see Are Golang function parameter passed as copy-on-write?; and Golang passing arrays to the function and modifying it.

    You have to start from a pointer, and you may use Value.Elem() to obtain the reflect.Value descriptor of the pointed, dereferenced value. But you must start from a pointer.

    Changing this single line in your code makes it work:

    v := reflect.ValueOf(&a).Elem()
    

    And also to print the type of a value, use the %T verb (%t is for bool values):

    fmt.Printf("%T
    
    ", v.Type())
    fmt.Printf("%T
    
    ", v.Type().Elem().Kind())
    
    // ...
    
    fmt.Printf("%T - %v", a, a)
    

    Output (try it on the Go Playground):

    Hello, playground
    *reflect.rtype
    
    reflect.Kind
    
    []string - [a b c d e]
    

    For a deeper understanding of Go's reflection, read the blog post: The Laws of Reflection

    And read related questions+answers:

    Assigning a value to struct member through reflection in Go

    Changing pointer type and value under interface with reflection

    Using reflection SetString

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)