02.3.4 关于unsafe包

你已经实际操作过unsafe包的东西了,现在来看一下为什么这个库这么特别。

首先,如果你看了unsafe包的源码,你可能会感到惊讶。在macOS Hight Sierra系统上,可以使用Homebrew安装1.9.1版本的Go 。unsafe源码路径在/usr/local/Cellar/go/1.9.1/libexec/src/unsafe/unsafe.go下面,不包含注释,它的内容如下

$ cd /usr/local/Cellar/go/1.9.1/libexec/src/unsafe/
$ grep -v '^//' unsafe.go|grep -v '^$'
package unsafe
type ArbitraryType int
type Pointer *ArbitraryType
func Sizeof(x ArbitraryType) uintptr
func Offsetof(x ArbitraryType) uintptr
func Alignof(x ArbitraryType) uintptr

OK,其它的unsafe包的go代码去哪里了?答案很简单:当你import到你程序里的时候,Go编译器实现了这个unsafe库。

许多系统库,例如runtime,syscallos会经常使用到usafe

Last updated