为什么闭包函数,内输出全局变量地址不同。请教了。

andylau004 · · 3191 次点击
很正常,闭包和方法是一样的,你传入的参数是复制的,两个指针的地址自然不一样。但两个指针指向的值却是一样的,这是两个不同的概念。你可以在闭包内外,通过"p"格式指令,对比一下: ```code package main import ( "fmt" "sync" ) var g_pMutex *sync.Mutex var g_iCount int32 func main() { fmt.Println( "Test_Mutex Beg" ) defer fmt.Println( "Test_Mutex End" ) fmt.Println( "" ) g_pMutex = new( sync.Mutex ) fmt.Printf( "g_pMutex=%p \n", g_pMutex ) fmt.Printf( "&g_pMutex=%p \n", &g_pMutex ) g_iCount = 0 pfnFunc := func ( pMutex *sync.Mutex ) { fmt.Println( "TestUse Beg" ) defer fmt.Println( "TestUse End" ) fmt.Printf( "pMutex=%p \n", pMutex ) fmt.Printf( "&pMutex=%p \n", &pMutex ) pMutex.Lock() defer pMutex.Unlock() g_iCount ++ } pfnFunc( g_pMutex ) fmt.Println("g_iCount=",g_iCount) } ```
#3
更多评论
结果,再发一次 2016-08-17 00:43:40 1471365820260269854 [Debug] t_Mutex.go:23 [Test_Mutex Beg] 2016-08-17 00:43:40 1471365820260280118 [Debug] t_Mutex.go:29 [g_pMutex=0XAEA460] 2016-08-17 00:43:40 1471365820260282767 [Debug] t_Mutex.go:35 [TestUse Beg] 2016-08-17 00:43:40 1471365820260284942 [Debug] t_Mutex.go:38 [pMutex=0XC82002C128] 2016-08-17 00:43:40 1471365820260287015 [Debug] t_Mutex.go:44 [TestUse End] 2016-08-17 00:43:40 1471365820260288973 [Debug] t_Mutex.go:48 [Test_Mutex End]
#1
![333.png](http://studygolang.qiniudn.com/160817/c20def1bc7af5edff6c5ce4ac5635521.png)
#2