dqteh7347 2019-03-18 18:49 采纳率: 100%
浏览 44
已采纳

在Go复制内存中执行切片分配

Purpose: I have a big buffer, and I would like to have an array/slice of pointer pointing to different loc in the buffer.

What I am doing:

datPtrs := make([][]byte, n)
for i:=0; i<n; i++{
    datPtrs[i] = bigBuf[i*m:(i+1)*m]
}

My Question:

  1. Will this copy memory? My guess is not, but I cannot find anywhere to confirm this.
  2. What is the best way/tool to find out whether there is memory copy or not?
  • 写回答

2条回答 默认 最新

  • dsfd3546 2019-03-18 18:56
    关注

    Go slices are implemented as a struct:

    src/runtime/slice.go:

    type slice struct {
        array unsafe.Pointer
        len   int
        cap   int
    }
    

    You are assigning/copying the slice struct, which does not copy the underlying array, only its pointer.


    A simple illustration:

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        buf := make([]byte, 8)
        for i := range buf {
            buf[i] = byte(i)
        }
        sub := buf[1:3]
        fmt.Println(buf)
        fmt.Println(sub)
        for i := range sub {
            sub[i] += 43
        }
        fmt.Println(buf)
        fmt.Println(sub)
    }
    

    Playground: https://play.golang.org/p/4OzPwuNmUlY

    Output:

    [0 1 2 3 4 5 6 7]
    [1 2]
    [0 44 45 3 4 5 6 7]
    [44 45]
    

    See The Go Blog: Go Slices: usage and internals,

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

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大