在另一个包中定义函数
Go function definition in another package
我正在阅读 this post 关于 time.startTimer 声明和定义的内容。
根据答案,time.startTimer 在 src/time/sleep.go
中声明
如下:
func startTimer(*runtimeTimer)
其定义在src/runtime/time.go
中如下:
func startTimer(t *timer) {
if raceenabled {
racerelease(unsafe.Pointer(t))
}
addtimer(t)
}
看来可以在一个.go文件中声明一个函数,在另一个.go文件中实现。我试过同样的方法,比如在a.go中声明一个函数,在b.go中实现,但是在go run a.go
中总是失败。这是这样做的正确方法吗?如何声明在另一个 .go 文件中实现的函数? sleep.go
或 time.go
中都没有 import
。 Go 是怎么做到的?
谢谢
如果你查看 startTimer
正文上方的行,你会看到一个针对 go 编译器的特殊指令:
//go:linkname stopTimer time.stopTimer
来自compile command documentation
//go:linkname localname importpath.name
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".
我正在阅读 this post 关于 time.startTimer 声明和定义的内容。
根据答案,time.startTimer 在 src/time/sleep.go
中声明
如下:
func startTimer(*runtimeTimer)
其定义在src/runtime/time.go
中如下:
func startTimer(t *timer) {
if raceenabled {
racerelease(unsafe.Pointer(t))
}
addtimer(t)
}
看来可以在一个.go文件中声明一个函数,在另一个.go文件中实现。我试过同样的方法,比如在a.go中声明一个函数,在b.go中实现,但是在go run a.go
中总是失败。这是这样做的正确方法吗?如何声明在另一个 .go 文件中实现的函数? sleep.go
或 time.go
中都没有 import
。 Go 是怎么做到的?
谢谢
如果你查看 startTimer
正文上方的行,你会看到一个针对 go 编译器的特殊指令:
//go:linkname stopTimer time.stopTimer
来自compile command documentation
//go:linkname localname importpath.name
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".