Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go function definition in another package

I am reading this post about time.startTimer declaration and definition.

From the answer, time.startTimer is declared in src/time/sleep.go as follows:

func startTimer(*runtimeTimer)

And its definition is in src/runtime/time.go as follows:

func startTimer(t *timer) {
    if raceenabled {
        racerelease(unsafe.Pointer(t))
    }
    addtimer(t)
}

So it seems that you can declare a function in one .go file and implement it in another .go file. I tried the same way, for example, declare a function in a.go and implement it in b.go, but it always failed when go run a.go. Is that the correct way to do so? How can I declare a function that is implemented in another .go file? There is no import in either sleep.go or time.go. How does Go do it?

Thanks

like image 520
password636 Avatar asked Dec 24 '22 10:12

password636


1 Answers

If you look on the line above the startTimer body, you will see a special directive for the go compiler:

//go:linkname stopTimer time.stopTimer

From the 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".

like image 87
JimB Avatar answered Jan 04 '23 05:01

JimB