指针的使用时机

huangapple go评论88阅读模式
英文:

When to use pointers

问题

我是你的中文翻译助手,以下是翻译好的内容:

我对Go语言还很陌生,对C/C++也只有一些基础知识,所以我对何时使用指针和何时不使用指针感到困惑。虽然这个问题可能没有确定的答案,但我想知道一些关于何时返回结构体和何时返回指针的指导原则(同样地,何时接受结构体/指针作为参数)。

根据我的猜测,以下观点是正确的:

  1. 结构体通过值传递给函数。也就是说,在将结构体传递给函数时会创建一个副本。
  2. 如果我想通过引用传递结构体,那么在函数定义中我应该使用指针参数,并在调用函数时使用取地址运算符。
  3. 我想通过引用传递结构体的原因是,要么我传递的结构体很大,在内存中传递副本会占用很多资源(不太可能),要么我想对传入的副本进行修改(更有可能)。
  4. 作为对第3点的推论,除非有以上原因需要通过引用传递,否则应该通过值传递。

我的假设正确吗?还是我对指针的理解有误?

英文:

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:

  1. structs are passed into functions by value. That is, a copy of a structure is made when passing it into a function.
  2. if I want to pass a structure by reference, then I would instead use a pointer argument in the function definition, and use the addressof operator when calling the function.
  3. The reason why I would want to pass in a structure by reference is because either the structure I'm passing in is large, and it would be taxing on memory to pass it by value (unlikely) or if I want to make changes to the copy that I'm passing in (more likely).
  4. As a corollary to 3.), I should pass by value unless I have one of the reasons above to pass by reference.

Are my assumptions correct? Or am I missing the mark on pointers?

答案1

得分: 31

你的假设是正确的。关于第三点,Go是一种并发语言,通过引用传递在goroutines中使它们都读取相同的结构是安全的,但也使它们修改相同的结构变得危险。

英文:

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.

huangapple
  • 本文由 发表于 2015年12月25日 02:07:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/34456429.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定