Home > Article > Backend Development > Does Go language have pass by reference?
The Go language does not have reference passing. There are no reference variables in the Go language. Each variable defined in the program occupies a unique memory location, so the Go language cannot create two variables that share the same memory location.
The environment of this article: Windows 10 system, Go 1.11.2 version, this article is applicable to all brands of computers.
(Learning video sharing: Programming video)
First of all, it must be clear that Go does not have reference variables, so there is no reference passing when calling functions in the Go language.
What is a reference variable?
In some development languages (such as C), aliases can be declared for existing variables. This alias is called a reference variable.
1#include <stdio.h> 2 3int main() { 4 int a = 10; 5 int &b = a; 6 int &c = b; 7 8 printf("%p %p %p\n", &a, &b, &c); // 0x7ffe114f0b14 0x7ffe114f0b14 0x7ffe114f0b14 9 return 0; 10}
You can see that a, b and c all point to the same memory location. Writing to a affects b and c. This is useful when you want to declare a reference variable in a different scope - i.e. when a function is called.
The Go language does not reference variables
Unlike C, each variable defined in a Go program occupies a unique memory location.
1package main 2 3import "fmt" 4 5func main() { 6 var a, b, c int 7 fmt.Println(&a, &b, &c) // 0x1040a124 0x1040a128 0x1040a12c 8}
It is not possible to create two variables that share the same memory location. It is possible to create two variables that point to the same memory location, but this is not the same as two variables sharing the same memory location.
1package main 2 3import "fmt" 4 5func main() { 6 var a int 7 var b, c = &a, &a 8 fmt.Println(b, c) // 0x1040a124 0x1040a124 9 fmt.Println(&b, &c) // 0x1040c108 0x1040c110 10}
In the above code, b and c both have the same value - that is, the address of variable a, but a and c are stored in different locations in memory. Changing the contents of b will not affect c.
map and channel are references?
wrong! map and channel are not references. If they were, the following code would output false.
If map m is a C-style reference variable, m declared in main() and m declared in fn() will share the same memory space. However, because assigning a value to m in fn() does not affect m in main(), we can see that map is not a reference variable.
Summary
Go does not pass by reference because Go does not have reference variables.
Related recommendations: golang tutorial
The above is the detailed content of Does Go language have pass by reference?. For more information, please follow other related articles on the PHP Chinese website!