doubaolan2842 2013-08-07 23:59
浏览 187
已采纳

在Go中使用反射设置切片索引

I'm in Go, working with a reflect.Value representation of a slice. I have the following:

slice := reflect.MakeSlice(typ, len, cap)

If I want to get the ith value from slice, it's simple:

v := slice.Index(i) // returns a reflect.Value

However, I can't seem to find a way to set the ith value. reflect.Value has lots of setter methods, for example, if I had a map, m, the following is possible:

m.SetMapIndex(key, value) // key and value have type reflect.Value

But there doesn't seem to be an equivalent for slices. My one thought was that maybe the value returned from slice.Index(i) is actually a pointer somehow, so calling v := slice.Index(i); v.Set(newV) would work? I'm not sure. Ideas?

  • 写回答

2条回答 默认 最新

  • duan0403788996 2013-08-08 00:05
    关注

    Figured it out! Turns out I posted this prematurely - my guess that slice.Index(0) returns a pointer was correct. In particular:

    one := reflect.ValueOf(int(1))
    
    slice := reflect.MakeSlice(reflect.TypeOf([]int{}), 1, 1)
    v := slice.Index(0)
    fmt.Println(v.Interface())
    
    v.Set(one)
    fmt.Println(v.Interface())
    
    v = slice.Index(0)
    fmt.Println(v.Interface())
    

    prints:

    0
    1
    1
    

    (Here's runnable code on the go playground)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?