8
头图

Recap

Recently, I have read many tutorials or blogs saying that 060d0b08fec7ea in slice、map、channel、func is "pass by reference". On the other hand, it is said that all types in golang are passed by value. It always feels like a cloud, so I did it myself. Test and think.

Here is the code part:

package main

import (
    "fmt"
)

func test(a *int) {
    fmt.Println("传入变量的值:", a)
    fmt.Println("传入变量的地址:", &a)
}

func main() {
    va := 666
    vad := &va
    fmt.Println("需要传入的值:", vad)
    fmt.Println("需要传入的值的地址", &vad)
    test(vad)
}

Here is the execution result

需要传入的值: 0xc000018658
需要传入的值的地址 0xc000006058
传入变量的值: 0xc000018658
传入变量的地址: 0xc000006060

Thinking and commentary

That is to say, the values passed in and actually received are pointer variables. The values of the two pointer variables vad and a are the address 0xc000018658 va pointed to by the pointer.

Then look at the address (pointer) 0xc000006060 a passed in the function, and compare the address 0xc000006058 vad stored outside. The two values are different, indicating that the pointer type is also value transfer, that is to say, it is copied A copy of the pointer value is passed to the function.

Therefore, the function test internal a variables and external vad variable is absolutely not the same thing, a is vad copy body, but the value of these two variables are stored va address of a variable, so the operation a be variable va is modified.

From this point of view, I personally feel that slice、map、channel、func is passed by reference" feels easy to cause misunderstanding. I suspect that golang treats these things specially, which is passed by reference.

In fact, in the design of golang , all types are passed in the form of values. It’s just that for these types, the underlying implementation is that after these types of data are successfully created, the data received by the variable is the address corresponding to these types, or the variable received by the assigned value is these few. The address of each type of value. It should not be the reference type of these types when they are passed.


kumfo
6.7k 声望4.1k 粉丝

程序生存法则: