go - 有什么方法可以通过引用传入数组的函数来传递数组?
问题描述
我更愿意将潜在的大数组传递给仅通过引用采用数组类型的标准函数,以避免每次都复制数组。
例如crypto/sha256
包Sum256()
函数https://golang.org/src/crypto/sha256/sha256.go?s=5634:5669#L244:
func Sum256(data []byte) [Size]byte
我的data
可能很大,我担心按值复制..看起来我可以传递一个切片并且编译器对此感到满意,但我不确定这是否仍会按值复制底层数组..
解决方案
切片是一个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
推荐阅读
- c++ - 我的程序没有错误就停止了,我做错了什么?
- python - Python MySQL Connector fetchone not returning dict
- security - 虚拟机 SharePoint 2013 问题 - SpFarm.Local 为空。本地机器可能不知道 VM 上的 SharePoint?
- docker - docker compose up 后,去后端到 redis 连接被拒绝
- angular - 如何在角度应用程序中部分导入引导程序?
- r - 在 R 中对具有相似名称/前缀的列求和
- flutter - 如何在不将旧根保存在堆栈中的情况下切换到新根?
- swift - 如何在 Swift 结果生成器中恢复类型泛型类型推断?
- bash - terraform 外部数据不返回 bash 输出
- firebase - 产品信息的多语言应用程序