go 突破訪問限制,訪問其他包中的私有變數

miss201發表於2018-11-09
 前幾天翻看 go 的原始碼的時候,發現了這個問題,
 mutex.go的程式碼的時候裡面的 func throw (string) 這個函式沒有方體,
 一般來說只有在介面裡定義的方法可以沒有方法體。

file

The //go:linkname directive instructs the compiler to use “importpath.name” 
as the object file symbol name for  the variable or function declared as “localname”
in the source code.
Because this directive can subvert the type system and package modularity, 
it is only enabled in files that have imported "unsafe".
這個指令告訴編譯器為函式或者變數localname使用importpath.name作為目標檔案的符號名。
因為這個指令破壞了型別系統和包的模組化,所以它只能在 import "unsafe" 的情況下才能使用。

go:linkname sync_throw sync.throw func sync_throw(s string) { throw(s) } 在panic.go 中定義的,
通過 go:linkname 指令將將當前(sync_throw)方法在編譯時連結到sync.throw,
throw函式是在 runtime/panic.go 中宣告的,但是注意看他首字母是小寫的,
所以為了突破訪問限制, 需要這麼宣告一下

不卑不亢,不慌不忙,這才是生活的模樣。

相關文章