何时使用指针 [英] When to use pointers
问题描述
我是Go语言的新手,并且在C/C ++中只有很少的背景知识,所以自然地,我在何时使用指针以及何时不使用指针的想法上苦苦挣扎.尽管这个问题可能被认为是开放式的,但我想知道关于何时返回结构和何时返回指针(以及等效地何时接受结构/指针作为参数)的一些指导原则.
I'm new to the Go Language, and have only minimal background in C/C++, so naturally I'm struggling with the idea of when to use pointers and when not to use pointers. Although this question might be considered open-ended, I'm wondering what some guidelines on when to return structs and when to return pointers, (and equivalently when to accept structs / pointers as arguments).
根据我的猜测,以下陈述成立:
From what I can guess, the following statements hold true:
- 结构按值传递给函数.也就是说,在将结构传递给函数时会对其进行复制.
- 如果我想通过引用传递结构,那么我会在函数定义中使用指针参数,并在调用函数时使用addressof运算符.
- 我之所以要通过引用传递结构的原因是,要么我传递的结构很大,要么按值传递(不太可能)对内存征税,或者如果我要传递更改我要传递的副本(更有可能).
- 作为3的必然推论,除非我有上述理由之一通过引用传递,否则我应该按值传递.
我的假设正确吗?还是我错过了指针上的标记?
Are my assumptions correct? Or am I missing the mark on pointers?
推荐答案
您的假设是正确的.关于#3,Go是并发语言,在goroutine中通过引用传递它们使它们都读取相同的结构,这是安全的,但也使它们修改了相同的结构,这是很危险的.
Your assumptions are correct. About #3, Go is concurrent language and passing by reference in goroutines make them all read same structure which is safe, but also make them modify same structure which is dangerous.
这篇关于何时使用指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!