Call by Value Vs Call by Reference.
Image by Author

Call by Value Vs Call by Reference.

In Go, it is generally recommended to use call by value, as it makes the code more predictable and easier to understand. However, there are certain situations where call by reference may be more appropriate.

Call by value should be used:

  • When the function is not going to modify the passed variable.
  • When the variable is a simple type (e.g., int, float, bool)
  • When the variable is a small struct or a small slice, and you don't want to create unnecessary copies.

Call by reference should be used:

  • When the function needs to modify the passed variable and the changes need to be reflected outside the function.
  • When the variable is a large struct or a large slice, and creating a copy would be costly in terms of memory and/or performance.
  • When you need to pass a variable to a function and you don't want to create a new variable.

Please keep in mind that in Go, the use of pointers must be done with caution, as it can lead to unexpected behavior and bugs if not used correctly.
Umesh Pawar

Software Developer | Node.js | React.js | Golang | MongoDB | SQL |

2 年

Very useful..

回复

要查看或添加评论,请登录

Radhakishan Surwase的更多文章

社区洞察

其他会员也浏览了