Pass by value in Go

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, call 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, band chave aan address, but band cthese two variables was stored in a different memory address, change the bvalue does not affect c.

mapAnd channelis 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 mainmiddle mis passed to the fnmiddle, then the processing by the function mshould have been initialized, but it can be seen that fnthe processing mhas no effect, so it mapis not a reference.

As for what map is? The next article will make it clear.

Guess you like

Origin www.cnblogs.com/Jun10ng/p/12723409.html