首页 > 解决方案 > 有什么方法可以通过引用传入数组的函数来传递数组?

问题描述

我更愿意将潜在的大数组传递给仅通过引用采用数组类型的标准函数,以避免每次都复制数组。

例如crypto/sha256Sum256()函数https://golang.org/src/crypto/sha256/sha256.go?s=5634:5669#L244

func Sum256(data []byte) [Size]byte 

我的data可能很大,我担心按值复制..看起来我可以传递一个切片并且编译器对此感到满意,但我不确定这是否仍会按值复制底层数组..

标签: go

解决方案


切片是一个struct包含指向数组(后备数组)的指针、长度和容量的切片。它描述了数组的一部分。当你复制一个切片时,Go 不会复制它的支持数组,Go 只复制切片。

// create an array of four bytes
dataArray := [4]byte{'d', 'a', 't', 'a'}

// get a slice of 'dataArray'.
// 'data' is just a struct that contains a pointer
// to the 'dataArray'. (data's backing array is
// dataArray).
data := dataArray[:]

// this only passes the `data`
// (which is a slice header of the data variable)
// it doesn't pass the `dataArray`.
//
// The only thing that is copied is the `data`
// (slice header) not the `dataArray`
// (the backing array of `data`).
sha256.Sum256(data)

如果您是视觉学习者,请观看此视频:https ://www.youtube.com/watch?v=fF68HELl78E


推荐阅读