當前位置:
首頁 >
Go unsafe Pointer
發布時間:2023/12/4
29
豆豆
生活随笔
收集整理的這篇文章主要介紹了
Go unsafe Pointer
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Go unsafe Pointer
Go被設計為一種強類型的靜態語言,強類型意味著類型一旦確定就無法更改,靜態意味著類型檢查在運行前就做了。
指針類型轉換
為了安全考慮,兩個不同類型的指針不能相互轉換,例如:
package mainfunc main() {i := 10ip := &ivar fp *float64 = (*float64)(ip)//會提示 Cannot convert an expression of the type '*int' to the type '*float64' 無法進行強制類型轉換 }如果非要進行轉換,可以使用unsafe包中的Pointer。
Pointer
unsafe.Pointer是一種特殊意義的指針。
package mainimport ("fmt""unsafe" )func main() {i := 10ip := &ifp := (*float64)(unsafe.Pointer(ip))*fp = *fp * 3fmt.Println(i) } //output: 30所以,使用unsafe.Pointer這個指針,我們可以在*T之間做任何轉換。可以看到Pointer是一個 *int。
type ArbitraryType int type Pointer *ArbitraryType我們可以看下關于unsafe.Pointer的四個原則:
對于后面兩個規則,我們知道*T是不能計算偏移量的,也不能進行計算。但是uintptr可以,我們可以把指針轉換為uintptr再進行偏移計算,這樣就可以訪問特定的內存了,例如:
type user struct {name stringage int }func main() {u := new(user)fmt.Println(*u)pName := (*string)(unsafe.Pointer(u))*pName = "demo"pAge := (*int)(unsafe.Pointer(uintptr(unsafe.Pointer(u)) + unsafe.Offsetof(u.age)))*pAge = 20fmt.Println(*u) } // output: {0} // {demo 20}最后
unsafe是不安全的,應該盡量少的去使用。
Package unsafe contains operations that step around the type safety of Go programs.
Packages that import unsafe may be non-portable and are not protected by the Go 1 compatibility guidelines.
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的Go unsafe Pointer的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 冲刺 1nm 制程,日本 Rapidus
- 下一篇: Slice的本质