This is a creation in Article, where the information may have evolved or changed.
My post on pointers provoked a lot of debate about maps and passes by reference semantics. This post was a response to those debates.
To is clear, go does not has reference variables, so go does not has pass-by-reference function call semantics.
What is a reference variable?
In languages like C + + you can declare a alias, or an alternate name to an existing variable. This is called a reference variable.
#include <stdio.h>int main () { int a = ten; int &b = A; int &c = b; printf ("%p%p%p\n", &a, &b, &c); 0x7ffe114f0b14 0x7ffe114f0b14 0x7ffe114f0b14 return 0;}
You can see this a
, b
and all c
refer to the same memory location. A write to would alter the contents of and a
b
c
. This is useful if you want to declare reference variables in different scopes–namely function calls.
Go does not has reference variables
Unlike C + +, each variable defined in a Go program occupies a unique memory location.
Package Mainimport "FMT" Func Main () { var A, b, c int FMT. Println (&a, &b, &c)//0x1040a124 0x1040a128 0x1040a12c}
It is not possible to create a Go program where the other variables share the same storage location in memory. It is possible to create a variables whose contents point to the same storage E thing as variables who share the same storage location.
Package Mainimport "FMT" Func Main () { var a int var b, C = &a, &a fmt. Println (b, c) //0x1040a124 0x1040a124 FMT. Println (&b, &c)//0x1040c108 0x1040c110}
In this example, b
and C hold the same value–the address a
of –however, b
and c
themselves is St ORed in unique locations. Updating the contents of b
would has no effect on c
.
But maps and channels is references, right?
Wrong. Maps and channels is not references. If They were this program would print false
.
Package Mainimport "FMT" func fn (M map[int]int) { m = make (Map[int]int)}func main () { var m map[int]int fn (m) C3/>fmt. Println (M = nil)}
If The map m
was a C + + style reference variable, the declared in and the m
main
declared in m
fn
would OCC Upy the same storage location in memory. But, because the assignment to m
inside have fn
no effect on m
the value of in main, we can see that maps is Not reference variables.
Conclusion
Go does not has pass-by-reference semantics because Go does not having reference variables.