【问题标题】:Any way to pass array by reference to function that takes an array? [closed]有什么方法可以通过引用传入数组的函数来传递数组? [关闭]
【发布时间】:2020-01-25 07:14:48
【问题描述】:

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

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

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

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

【问题讨论】:

  • 切片是三个机器字:指向后备数组的指针、长度和容量。切片在调用中被复制,但不是支持数组。问题中显示的函数有一个切片参数,而不是数组参数。
  • 很酷的声音就像传递一个切片是要走的路,如果你输入答案我会标记它:)
  • 将数组传递给切片参数是编译错误。使用 slice expression 在数组上创建切片。将调用问题分开,听起来您应该使用切片而不是数组。当长度较大或大小未知时,通常使用切片。
  • 这能回答你的问题吗? Does slice assignment in Go copy memory

标签: go


【解决方案1】:

切片是一个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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-10
    • 2020-12-07
    • 1970-01-01
    • 2011-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多