Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

GO 值传递 #63

Open
git-zjx opened this issue Jun 18, 2020 · 1 comment
Open

GO 值传递 #63

git-zjx opened this issue Jun 18, 2020 · 1 comment
Assignees
Labels
Go Go Tips Tips
Projects

Comments

@git-zjx
Copy link
Owner

git-zjx commented Jun 18, 2020

go 一直都是值传递,只不过有时候传递的是引用类型,例如:指针、map、slice、chan,这些可以在函数内修改原内容数据

@git-zjx git-zjx added this to Tips in Go Aug 4, 2020
@git-zjx git-zjx self-assigned this Aug 4, 2020
@git-zjx git-zjx added Go Go Tips Tips labels Aug 4, 2020
@git-zjx
Copy link
Owner Author

git-zjx commented Oct 23, 2020

这里更详细些

slice 类型的虽然打印出了的内存地址不一样,但是还能修改原始的值

func main() {
        sliceA := make([]int, 1, 1)
	fmt.Printf("sliceA : %p , %v\n", &sliceA, sliceA)
	testSlice(sliceA)
	fmt.Printf("sliceA : %p , %v\n", &sliceA, sliceA)
}
func testSlice(x []int) {
	x[0] = 1
	fmt.Printf("func sclice : %p , %v\n", &x, x)
}

结果:

sliceA : 0x120940e0 , [0]
func sclice : 0x12094100 , [1]
sliceA : 0x120940e0 , [1]

出现这种情况在于 slice 的结构体内存储了一个指向数组的指针 :

type slice struct {
    array unsafe.Pointer
    len   int
    cap   int
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Go Go Tips Tips
Projects
Go
Tips
Development

No branches or pull requests

1 participant