duanji9481 2016-10-24 17:00
浏览 178
已采纳

将reflect.AppendSlice的结果分配给指针

I have troubles translating this piece of code, which is effectively a left rotate on a slice, into a more generic version which accepts interface{} as an input parameter.

func rotate(a *[]int, i int) {
    x, b := (*a)[:i], (*a)[i:]
    *a = append(b, x...)
}

I have troubles with the final assignment:

func rotateSlice(a interface{}, i int) {
    v := reflect.ValueOf(a)
    x, b := v.Elem().Slice(0, i), v.Elem().Slice(i, v.Elem().Len())
    *a = reflect.AppendSlice(b, x)
}

The error message is invalid indirect of a (type {}). The value of a is interface{}, hence *a = would be to assign the right-hand value to the space where the pointer is pointing to. My call to AppendSlice returns Value though. I am not sure where the type assertion needs to happen, I suppose on the left-hand side?

  • 写回答

2条回答 默认 最新

  • dousi5501 2016-10-24 17:08
    关注

    a is an interface{} not a pointer, so you can't dereference it. Even if you have a pointer to a slice, you can't assigned the result ofreflect.AppendSlice, because it returns the type reflect.Value. You need to set the value via Value.Set.

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

    func rotateSlice(a interface{}, i int) {
        v := reflect.ValueOf(a).Elem()
        x, b := v.Slice(0, i), v.Slice(i, v.Len())
        v.Set(reflect.AppendSlice(b, x))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算