Home  >  Article  >  Backend Development  >  Are Go Channels Passed by Reference or Value?

Are Go Channels Passed by Reference or Value?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-17 18:46:02684browse

Are Go Channels Passed by Reference or Value?

Are Channels Implicitly Passed by Reference?

The Go tour provides an example of channels that raises questions about their passing mechanism. By passing a channel into the sum function, the changes made to it within the function persist, leaving open the possibility of implicit reference passing.

Explanation

Technically, channels are copied when passed because make creates heap-allocated memory that effectively acts as a pointer. However, this pointer is not exposed, allowing channels to be treated as reference types.

The specification clarifies that the built-in make function returns a value of type T (not *T) and initializes the memory. When used with channels, make initializes the channel and makes it usable as a reference type.

Implications

This behavior means that when you pass channels created with make into functions, you can read and write to them without copying the underlying data.

Reference Types vs Value Types

The following types are passed by reference in Go:

  • Slices
  • Maps
  • Channels
  • Pointers
  • Functions

Data types like numbers, bools, and structs are copied when passed into functions.

The above is the detailed content of Are Go Channels Passed by Reference or Value?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn