Go:调用将指针传递给数组的函数
我花了一些时间尝试执行此操作,我认为我需要一个全局数组(而不是切片),并且我想将其作为指针传递,而不是按值传递。接收指针的函数需要测试nil,如果nil,则使用例如“baForm,oOserr = ioutil.ReadFile(sFormName)”从磁盘读取数组。调用函数可以传递一个全局数组或调用函数的本地数组,我认为这些数组将被垃圾收集。
这样做的原因是我想要一个标准函数从磁盘读取表单,并且经常使用的表单存储在全局中。尽管有些人可能认为有更好的方法,但我仍然想知道如何实现这一点,即:a)有全局或本地数组,b)不按值传递,c)全局数组将仅从磁盘读取一次并且每次调用该函数时都会读取本地数组。 TIA。
I have spent a bit of time attempting to do this, and I think I need a global array (not slice), and I want to pass it as a pointer, not by value. The function receiving the pointer needs to test for nil, and if nil, read the array from disk, using eg: "baForm, oOserr = ioutil.ReadFile(sFormName)". The calling function may pass either a global array or an array local to the calling function which I presume will be garbage collected.
The reason for doing this is that I want a standard function to read the forms from disk, and often-used forms are stored globally. Despite whether some may think there is a better way, I still want to know how to achieve this ie: a) have global or local array, b) not pass by value, c) The global arrays will be read only once from disk and the local arrays will be read each time the function is called. TIA.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通过阅读你的描述,我不明白为什么传递一个指向数组的指针比传递一个切片更好——但这取决于你。
您可以像在 C 中一样传递指针 - 将星号 (
*
) 附加到声明,并在值上附加一个与号 (&
)调用该函数。请记住,在 Go 中,数组大小是其类型的一部分。这意味着您的函数声明将嵌入数组大小,因此您无法使用任何不同大小的数组调用该函数。仅这个原因就足以保证使用切片而不是数组。
From reading your description, I can't see why passing a pointer to an array is any way better than passing a slice -- but it's up to you.
You can pass a pointer just like you do in C -- attach an asterisk (
*
) to the declaration, and perpend an ampersand (&
) to the value when you call the function.Just remember that in Go, the array size is part of its type. This means that your function declaration will have the array size embedded into it, so you can't call the function using an array of any different size. This reason alone is generally enough to warrant using a slice instead of an array.
这是一个示例程序,它根据使用计数维护动态表单缓冲区。如果 ReadForm 函数找到一个表单,它将返回该表单的地址和一个 nil 错误。
编辑:映射操作不是原子的。修改示例程序以使用互斥体进行并发访问到
forms
地图。Here's a sample program that maintains a dynamic forms buffer based on use count. If the ReadForm function finds a form, it returns the address of the form and a nil error.
EDIT: Map operations are not atomic. Revise the sample program to use a mutex for concurrent access to the
forms
map.