duansha3771 2017-12-27 05:48
浏览 26
已采纳

我可以恢复从切片开始处切片的元素吗?

a := []int{1,2,3,4,5,6}
b := a[1:len(a)-1]
fmt.Println(b) // -> [2 3 4 5]

I can get the 6 back from b:

c := b[:len(b)+1]
fmt.Println(c) // -> [2 3 4 5 6]

But can I get the 1 back?

If I try

c := b[-1:]

I get

invalid slice index -1 (index must be non-negative)

If I can't get it back, does it mean it will be garbage collected?

  • 写回答

1条回答 默认 最新

  • duanmo5724 2017-12-27 06:07
    关注

    It will not be garbage collected:Go Slices: usage and internals

    If you read this answer it shows you how to use reflection to get the underlying array, from which 1 is recoverable using unsafe and reflect packages.

    s := []int{1, 2, 3, 4}
    hdr := (*reflect.SliceHeader)(unsafe.Pointer(&s))
    data := *(*[4]int)(unsafe.Pointer(hdr.Data))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置