Skip to content

Latest commit

 

History

History
18 lines (14 loc) · 988 Bytes

File metadata and controls

18 lines (14 loc) · 988 Bytes

有关 unsafe 包

现在你已经看到了unsafe包在起作用,现在该讨论更多有关使其成为特殊程序包的方法了。首先,如果你查看unsafe包的源代码,你可能会有些惊讶。在使用 Homebrew(https://brew.sh/)安装的 Go 版本为 1.11.4 的 macOS Mojave 系统上,unsafe包的源代码位于/usr/local/Cellar/go/1.11.4/libexec/src/unsafe/unsafe.go,不包含注释,它的内容如下:

  $ cd /usr/local/Cellar/go/1.11.4/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

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

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