Golang selected blog post translation warehouse
original address
Let's make it clear that there are no reference variables in go, so there is no reference to value.
What is a reference variable?
In a C ++-like language, you can declare an alias and put a different name on a variable. We call this a reference variable.
#include <stdio.h>
int main() {
int a = 10;
int &b = a;
int &c = b;
printf("%p %p %p\n", &a, &b, &c); // 0x7ffe114f0b14 0x7ffe114f0b14 0x7ffe114f0b14
return 0;
}
As you can see a
, b
, c
all point to the same memory address, the value of the three, when you want to declare reference variables (ie function call) at different ranges, this feature is useful.
There is no reference variable in go
Unlike C ++, each variable in go has a unique memory address.
package main
import "fmt"
func main() {
var a, b, c int
fmt.Println(&a, &b, &c) // 0x1040a124 0x1040a128 0x1040a12c
}
You can't find two variables in the go program sharing a memory, but you can make the two variables point to the same memory.
package main
import "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
have a
an address, but b
and c
these two variables was stored in a different memory address, change the b
value does not affect c
.
map
And channel
is it quoted?
No, neither map nor channel are references. If they are, the following example will outputfalse
package main
import "fmt"
func fn(m map[int]int) {
m = make(map[int]int)
}
func main() {
var m map[int]int
fn(m)
fmt.Println(m == nil)
}
If it is a reference variable, the main
middle m
is passed to the fn
middle, then the processing by the function m
should have been initialized, but it can be seen that fn
the processing m
has no effect, so it map
is not a reference.
As for what map is? The next article will make it clear.