郑州哪家公司给国外做网站,东营网站设计多少钱,网络营销优化推广公司,网站吸引用户Go unsafe Pointer
Go被设计为一种强类型的静态语言#xff0c;强类型意味着类型一旦确定就无法更改#xff0c;静态意味着类型检查在运行前就做了。
指针类型转换
为了安全考虑#xff0c;两个不同类型的指针不能相互转换#xff0c;例如#xff1a;
package mainfun…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 (fmtunsafe
)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的四个原则 任何指针都可以转换为unsafe.Pointerunsafe.Pointer可以转换为任何指针uintptr可以转换为unsafe.Pointerunsafe.Pointer可以转换为uintptr 对于后面两个规则我们知道*T是不能计算偏移量的也不能进行计算。但是uintptr可以我们可以把指针转换为uintptr再进行偏移计算这样就可以访问特定的内存了例如
type user struct {name stringage int
}func main() {u : new(user)fmt.Println(*u)pName : (*string)(unsafe.Pointer(u))*pName demopAge : (*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.